首页 > 代码库 > C#循环枚举得到枚举的注释和值

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);
            }
        }

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