How to get all descriptions of enum values with reflection?

前端 未结 7 1472
孤独总比滥情好
孤独总比滥情好 2021-02-10 08:29

So I need to get a List from my enum

Here is what I have done so far:

enum definition

           


        
7条回答
  •  一向
    一向 (楼主)
    2021-02-10 08:52

    I created these extension methods

    public static class EnumExtender
    {
        public static string GetDescription(this Enum enumValue)
        {
            string output = null;
            Type type = enumValue.GetType();
            FieldInfo fi = type.GetField(enumValue.ToString());
            var attrs = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
            if (attrs.Length > 0) output = attrs[0].Description;
            return output;
        }
    
        public static IDictionary GetEnumValuesWithDescription(this Type type) where T : struct, IConvertible
        {
            if (!type.IsEnum)
            {
                throw new ArgumentException("T must be an enumerated type");
            }
    
            return type.GetEnumValues()
                    .OfType()
                    .ToDictionary(
                        key => key,
                        val => (val as Enum).GetDescription()
                    );
        }
    }
    

    Usage

    var stuff = typeof(TestEnum).GetEnumValuesWithDescription();
    

    Will return a Dictionary with value as keys and descriptions as values. If you want just a list, you can change .ToDictionary to

    .Select(o => (o as Enum).GetDescription())
    .ToList()
    

提交回复
热议问题