• Home
  • 简单生活
  • 一般技术
  • .NET
  • XML-RPC
  • FreeBSD
  • Linux
  • Python
  • Database
  • 书籍阅读
  • 电视电影
  • 网站相关
  • 乱七八糟
  • 娱记
  • 常用软件
  • 标签云

  • 获取枚举描述信息(Description)

    2009年06月26日 enum 枚举描述信息

    看到别人的enum都有一个获取枚举描述信息(Description),直接给自己的加上,发现not work。网上找了找,原来要这个样子加的:

    1。定义enum
    using System;
    using System.ComponentModel;

      public enum TimeOfDay
            {
                [Description("上午")]
                Moning = 0,
                [Description("中午")]
                Afternoon = 1,
                [Description("晚上")]
                Evening = 2,
            };
     

    2。得到enum的描述信息。以NameValueCollection返回。

    NameValueCollection的key值等于enum的key。
     

    using System;
    using System.Reflection;
    using System.ComponentModel;
    using System.Collections.Specialized; 

       /// <summary>
        /// 得到enum的属性值
        /// </summary>
        /// <returns></returns>
        public static NameValueCollection ConvertEnumDescriptionValue()
        {
           
            NameValueCollection nvc = new NameValueCollection();
            Type type = typeof(DescriptionAttribute);
          
            foreach (FieldInfo fi in typeof(EnumClass.TimeOfDay).GetFields())
            {
                object[] arr = fi.GetCustomAttributes(type, true);
                if (arr.Length > 0)
                {
                   
                    nvc.Add(fi.Name, ((DescriptionAttribute)arr[0]).Description);
                }
            }

            return nvc;

        }

    发表评论

    *必填

    *必填 (不会被公开)

    *
    To prove you're a person (not a spam script), type the security word shown in the picture.
    Anti-Spam Image