一个利用扩展方法的实例:AttachDataExtensions (改良老赵方法)

本文介绍了一种通过自定义属性和扩展方法为枚举项附加数据的方法,并提供了多语言支持的实现示例。

          参考老赵方法后改了一下.

原帖:http://www.cnblogs.com/JeffreyZhao/archive/2009/01/07/AttachDataExtensions.html

 

 

自定义属性:

 

using System;

namespace System
{
    /// <summary>
    /// 枚举附加数据属性
    /// </summary>
    [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
    public class AttachDataAttribute : Attribute
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="value">附加的数据</param>
        public AttachDataAttribute(object value)
        {
            this.Key = value.GetType().FullName;
            this.Value = value;
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="key">指定附加的数据的Key</param>
        /// <param name="value">附加的数据</param>
        public AttachDataAttribute(string key, object value)
        {
            this.Key = key;
            this.Value = value;
        }

        public string Key { get; private set; }

        public object Value { get; private set; }
    }
}

 

 

扩展方法:

 

 

using System.Collections.Generic;
using System.Reflection;

namespace System
{
    /// <summary>
    /// 取得枚举附加数据
    /// </summary>
    public static class Extensions
    {
        /// <summary>
        /// 取得枚举附加数据
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="field">枚举本身</param>
        /// <returns>返回对应的数据类型的数据,如没有对应类型的数据返回default(T)</returns>
        public static T GetValue<T>(this Enum field)
        {
            return field.GetValue<T>(typeof(T).FullName);
        }

        /// <summary>
        /// 取得枚举附加数据
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="field">枚举本身</param>
        /// <param name="key">取数据的Key</param>
        /// <returns>返回对应的数据类型的数据,如没有对应类型的数据返回default(T)</returns>
        public static T GetValue<T>(this Enum field, string key)
        {
            object obj = field.GetValue(key);
            return obj == null ? default(T) : (T)obj;
        }

        /// <summary>
        /// 取得枚举附加数据
        /// </summary>
        /// <param name="field">枚举本身</param>
        /// <returns>返回对应的object的数据,如没有对应类型的数据返回null</returns>
        public static object GetValue(this Enum field)
        {
            return field.GetType().GetField(field.ToString()).GetAttachData();
        }

        /// <summary>
        /// 取得枚举附加数据
        /// </summary>
        /// <param name="field">枚举本身</param>
        /// <param name="key">取数据的Key</param>
        /// <returns>返回对应的object的数据,如没有对应类型的数据返回null</returns>
        public static object GetValue(this Enum field, string key)
        {
            return field.GetType().GetField(field.ToString()).GetAttachData(key);
        }

        private static object GetAttachData(this ICustomAttributeProvider provider)
        {
            return GetAttachData(provider, "");
        }

        private static object GetAttachData(this ICustomAttributeProvider provider, string key)
        {
            AttachDataAttribute[] attributes = (AttachDataAttribute[])provider.GetCustomAttributes(typeof(AttachDataAttribute), false);

            if (string.IsNullOrEmpty(key))
            {
                return attributes.Length > 0 ? attributes[0].Value : null;
            }

            foreach (AttachDataAttribute item in attributes)
            {
                if (item.Key == key)
                {
                    return item.Value;
                }
            }
            //   AttachDataAttribute item=  attributes.fild(a => a.Key.Equals(key));
            return null;
        }

        public static IDictionary<string, object> data { get; set; }

        public static void AddTagValue<T>(this Enum field, string key, T value)
        {
            if (data == null)
            {
                data = new Dictionary<string, object>();
            }

            lock (data)
            {
                string k = GetDataKey(field, key);
                if (!data.ContainsKey(k))
                {
                    data.Add(k, value);
                }
            }
        }


        private static string GetDataKey(Enum field, string key)
        {
            return string.Format("{0}.{1},{2}", field.GetType().FullName, field, key);

        }

        public static T GetTagValue<T>(this Enum field, string key)
        {
            string k = GetDataKey(field, key);
            if (data.ContainsKey(k))
            {
                return (T)data[k];
            }
            return default(T);

        }
    }
}

 

 

示例:

 

/// <summary>
    /// 心电采集类型
    /// </summary>
    public enum CollectType
    {
        /// <summary>
        /// 无
        /// </summary>
        [AttachData("无")]
        None,

        /// <summary>
        /// 快速测量
        /// </summary>
        [AttachData("快速测量")]
        Fast,

        /// <summary>
        /// 普通测量
        /// </summary>
        [AttachData("普通测量")]
        Normal,

        /// <summary>
        /// 增强测量
        /// </summary>
        [AttachData("增强测量")]
        Enhanced
    }

 

 

        多语言:

        /// <summary>
        /// Inits the context.
        /// </summary>
        public void InitContext()
        {
            CollectType.None.AddTagValue("EN", "None");
            CollectType.None.AddTagValue("CN", "无");
         
            CollectType.Fast.AddTagValue("EN", "Fast");
            CollectType.Fast.AddTagValue("CN", "快速测量");
           
            CollectType.Normal.AddTagValue("EN", "Normal");
            CollectType.Normal.AddTagValue("CN", "普通测量");
           
            CollectType.Enhanced.AddTagValue("EN", "Enhanced");
            CollectType.Enhanced.AddTagValue("CN", "增强测量");
        }

 

 

    string CollectType = DataContext.CollectMethod.GetTagValue<string>("CN");

       或

     string CollectType = DataContext.CollectMethod.GetValue<string>();

 

 

老赵的这个方法是这样的:

 

    public static object GetAttachedData(
        this ICustomAttributeProvider provider, object key)
    {
        var attributes = (AttachDataAttribute[])provider.GetCustomAttributes(
            typeof(AttachDataAttribute), false);
        return attributes.First(a => a.Key.Equals(key)).Value;
    }

 

这个方法.有个问题就是使用了 First ,First方法当集合内没有要找的值是就是出错.所以这里换成了foreach ,谁会在一个枚举成员上加成百上千个属性呢.所以性能不会比First差什么的.

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值