zoukankan      html  css  js  c++  java
  • 获取枚举描述信息(Description)

    工作中,碰到了这样一个问题。想在代码中定义几个常用的值。

    常用方法

    1)写在每个界面中。

    2)struct中定义

    3) config文件定义

    4)用enum。

    方法1)的可维护行太差,不可取。方法2)的封装性太差。现在用方法4)解决。

    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;

        }

    引用博客http://www.cnblogs.com/yank/archive/2009/02/27/1399423.html。

    感谢yank

  • 相关阅读:
    HDU1029 Ignatius and the Princess IV
    UVA11039 Building designing【排序】
    UVA11039 Building designing【排序】
    POJ3278 HDU2717 Catch That Cow
    POJ3278 HDU2717 Catch That Cow
    POJ1338 Ugly Numbers(解法二)
    POJ1338 Ugly Numbers(解法二)
    UVA532 Dungeon Master
    UVA532 Dungeon Master
    POJ1915 Knight Moves
  • 原文地址:https://www.cnblogs.com/chinaagan/p/1400576.html
Copyright © 2011-2022 走看看