欢迎加我的QQ群:193522571,一起来讨论、交流!

C#循环枚举得到枚举的注释和值

 

复制代码
首先定义一个枚举
/// <summary> /// 枚举注释的自定义属性类 /// </summary> public class EnumDescriptionAttribute : Attribute { private string m_strDescription; public EnumDescriptionAttribute(string strPrinterName) { m_strDescription = strPrinterName; } public string Description { get { return m_strDescription; } } } /// <summary> /// 测试类型 /// </summary> public enum TestType { /// <summary> /// 分静态精度测量 /// </summary> [EnumDescription("分静态精度测量")] StaticPrecisionOpen, /// <summary> /// 合静态精度测量 /// </summary> [EnumDescription("合静态精度测量")] StaticPrecisionClose, /// <summary> /// 副分静态精度测量 /// </summary> [EnumDescription("副分静态精度测量")] StaticPrecisionOPenSec, /// <summary> /// 频谱分析 /// </summary> [EnumDescription("频谱分析")] Dynamic, /// <summary> /// 分电流峰值 /// </summary> [EnumDescription("分电流峰值")] CurMaxOpen, /// <summary> /// 合电流峰值 /// </summary> [EnumDescription("合电流峰值")] CurMaxClose }
复制代码

接下来通过循环得到枚举的值和注释

复制代码
 Dictionary<string, int> enumDic = new Dictionary<string, int>();

        public void ForEnum()
        {
            Type t = typeof(TestType);
            Array arrays = Enum.GetValues(t);
            for (int i = 0; i < arrays.LongLength; i++)
            {
                TestType test = (TestType)arrays.GetValue(i);
                FieldInfo fieldInfo = test.GetType().GetField(test.ToString());
                object[] attribArray = fieldInfo.GetCustomAttributes(false);
                EnumDescriptionAttribute attrib = (EnumDescriptionAttribute)attribArray[0];
                enumDic.Add(attrib.Description, (int)test);
            }
        }
复制代码
 
posted @ 2017-03-14 09:55  swtool  阅读(9082)  评论(0编辑  收藏  举报
欢迎加我的QQ群:193522571,一起来讨论、交流!