.net c# 获取枚举值集合与其属性

直接上代码,加入有如下枚举

    public enum EMyType
    {
        [System.ComponentModel.Description("A类型")]
        TypeA = 1,
        [System.ComponentModel.Description("B类型")]
        TypeB = 1,
        [System.ComponentModel.Description("C类型")]
        TypeC = 2,
    }  
接着遍历其枚举名的方法是

            foreach (var name in Enum.GetNames(typeof(EMyType)))
            {
                Console.WriteLine(name);
            }
接着遍历其枚举名与枚举值的方法是

            foreach (var value in Enum.GetValues(typeof(EMyType)))
            {
                Console.WriteLine(string.Format("{0}={1}", value.ToString(), Convert.ToInt32(value)));
            }
接着遍历其枚举名,枚举值与描述属性的字符串的方法是

            foreach (var value in Enum.GetValues(typeof(EMyType)))
            {
                object[] objAttrs = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (objAttrs != null && 
                    objAttrs.Length > 0)
                {
                    DescriptionAttribute descAttr = objAttrs[0] as DescriptionAttribute;
                    Console.WriteLine(string.Format("[{0}]", descAttr.Description));
                }
                Console.WriteLine(string.Format("{0}={1}", value.ToString(), Convert.ToInt32(value)));
            }





你可能感兴趣的:(.net c# 获取枚举值集合与其属性)