• 获取枚举描述信息(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

  • 相关阅读:
    [Panzura] identify user operations(copy, open, read ... ) in audit log
    Spark 学习
    Zeppelin 学习
    Delta Lake 学习
    传染病模型 SI
    xcodebuild和xcrun实现自动打包iOS应用程序
    控制UIlabel 垂直方向对齐方式的 方法
    ALAssetsLibrary
    CATransform3D
    AVFoundation的使用
  • 原文地址:https://www.cnblogs.com/chinaagan/p/1400576.html
Copyright © 2020-2023  润新知