C# 给枚举定义DescriptionAttribute,把枚举转换为键值对

http://www.cnblogs.com/lyl6796910/p/3958768.html

首先给枚举类型添加获得描述信息的方法类,如下:

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


namespace EnumExtensions
{
    /// <summary>
    /// 枚举实用操作
    /// </summary>
    public static class EnumUtil
    {
        /// <summary>
        /// 把枚举转换为键值对集合
        /// </summary>
        /// <param name="enumType">枚举类型</param>
        /// <param name="getText">以Enum为参数类型,String为返回类型的委托</param>
        /// <returns>以枚举值为key,枚举文本为value的键值对集合</returns>
        public static Dictionary<Int32, String> EnumToDictionary(Type enumType, Func<Enum, String> getText)
        {
            if (!enumType.IsEnum)
            {
                throw new ArgumentException("传入的参数必须是枚举类型!", "enumType");
            }
            Dictionary<Int32, String> enumDic = new Dictionary<int, string>();
            Array enumValues = Enum.GetValues(enumType);
            foreach (Enum enumValue in enumValues)
            {
                Int32 key = Convert.ToInt32(enumValue);
                String value = getText(enumValue);
                enumDic.Add(key, value);
            }
            return enumDic;
        }


        /// <summary>
        /// 在指定枚举中检索具有指定值的描述信息
        /// </summary>
        /// <param name="enumType">枚举类型</param>
        /// <param name="value">特定枚举常数的值(根据其基础类型)</param>
        /// <param name="nameInstead">当枚举值没有定义DescriptionAttribute,是否使用枚举名代替,默认是使用</param>
        /// <returns>enumType的枚举常数的描述信息,如果没有找到这样的枚举常数,则为null。</returns>
        public static String GetDescription(Type enumType, object value, Boolean nameInstead = true)
        {
            Enum e = (Enum)Enum.ToObject(enumType, value);
            return e == null ? null : e.GetDescription(nameInstead);
        }


        /// <summary>
        /// 扩展方法,获得枚举的Description
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <param name="nameInstead">当枚举值没有定义DescriptionAttribute,是否使用枚举名代替,默认是使用</param>
        /// <returns>枚举的Description</returns>
        public static string GetDescription(this Enum value, Boolean nameInstead = true)
        {
            Type type = value.GetType();
            string name = Enum.GetName(type, value);
            if (name == null)
            {
                return null;
            }


            FieldInfo field = type.GetField(name);
            DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;


            if (attribute == null&&nameInstead == true)
            {
                return name;
            }
            return attribute == null ? null : attribute.Description;
        }
    }

}


在实例中代码引用该命名空间,即可

如:

using EnumExtensions;


public enum Url
        {
            [Description("http://www.thylx.net")]
            个人博客 = 1,
            [Description("http://blog.163.com/thylx133@126/")]
            网易博客 = 2,
            [Description("http://www.8eshare.com/")]
            八邑分享 = 3
        }

Url test = Url.八邑分享;
string newstring = test.GetDescription();


using System;
using System.Collections.Generic;
using System.ComponentModel;


namespace EnumExtensions
{
    public enum Season
    {
        [Description("春 天")]
        Spring = 1,
        [Description("夏 天")]
        Summer = 2,
        //[Description("秋 天")]
        Autumn = 3,
        [Description("冬 天")]
        Winter = 4
    }
    class Program
    {
        static void Main(string[] args)
        {
            Season spring = Season.Spring;
            //打印枚举名
            Console.WriteLine(spring.ToString());
            //打印枚举说明
            Console.WriteLine(spring.GetDescription());


            //枚举转换为键值对集合
            Dictionary<Int32, String> dic = EnumUtil.EnumToDictionary(typeof(Season), e => e.GetDescription());
            PrintDic(dic);


            dic = EnumUtil.EnumToDictionary(typeof(Season), e => e.GetDescription(false));
            PrintDic(dic);


            dic = EnumUtil.EnumToDictionary(typeof(Season), e => e.ToString());
            PrintDic(dic);


            dic = EnumUtil.EnumToDictionary(typeof(Season), e => Enum.GetName(typeof(Season), e));
            PrintDic(dic);


            Console.ReadLine();
        }


        private static void PrintDic(Dictionary<Int32, String> dic)
        {
            foreach (KeyValuePair<Int32,String> item in dic)
            {
                Console.WriteLine("Key:{0}-----Value:{1}", item.Key, item.Value);
            }
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值