如何获取枚举值和描述的列表?

时间:2015-01-15 07:51:28

标签: enums

我有以下枚举:

public enum AlertSeverity
    {
        [Description("Informative")]
        Informative = 1,

        [Description("Low risk")]
        LowRisk = 2,

        [Description("Medium risk")]
        MediumRisk = 3,

        [Description("High risk")]
        HighRisk = 4,

        Critical = 5
    }

我希望获得所有描述/名称和值的List<KeyValuePair<string, int>>, 所以我尝试过这样的事情:

public static List<KeyValuePair<string, int>> GetEnumValuesAndDescriptions<T>() where T : struct
    {
        var type = typeof(T);
        if (!type.IsEnum)
            throw new InvalidOperationException();
        List<KeyValuePair<string, int>> lst = new List<KeyValuePair<string, int>>();
        foreach (var field in type.GetFields())
        {
            var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; // returns null ???
            if (attribute != null)
                lst.Add(new KeyValuePair<string, int>(attribute.Description, ((T)field.GetValue(null)).ToInt()));
            else
                lst.Add(new KeyValuePair<string, int>(field.Name, ((T)field.GetValue(null)).ToInt())); // throws exception: "Non-static field requires a target" ???
        }
        return lst;
    }

我不知道为什么但是属性var返回null而field.Name抛出异常&#34;非静态字段需要目标&#34;

1 个答案:

答案 0 :(得分:9)

这应该有效:

public static List<KeyValuePair<string, int>> GetEnumValuesAndDescriptions<T>()
        {
            Type enumType = typeof (T);

            if (enumType.BaseType != typeof(Enum))
                throw new ArgumentException("T is not System.Enum");

            List<KeyValuePair<string, int>> enumValList = new List<KeyValuePair<string, int>>();

            foreach (var e in Enum.GetValues(typeof(T)))
            {
                var fi = e.GetType().GetField(e.ToString());
                var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

                enumValList.Add(new KeyValuePair<string, int>((attributes.Length > 0) ? attributes[0].Description : e.ToString(), (int)e));
            }

            return enumValList;
        }