Getting Description Attribute of a Generic Enum

前端 未结 3 1998
臣服心动
臣服心动 2021-01-14 05:30

I\'m having some hard time with trying to be generic with enums. I\'ve read that it\'s not that simple, and I can\'t seem to find a solution.

I\'m trying to create a

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-14 06:07

    I took the liberty of modifying some parts of the code, like changing the return types to more C# standard API return values.

    You can watch it run here.

    public static EnumDescription ConvertEnumWithDescription() where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException("Type given T must be an Enum");
        }
    
        var enumType = typeof(T).Name;
        var valueDescriptions = Enum.GetValues(typeof (T))
            .Cast()
            .ToDictionary(Convert.ToInt32, GetEnumDescription);
    
        return new EnumDescription
        {
            Type = enumType,
            ValueDescriptions = valueDescriptions
        };
    
    }
    
    public static string GetEnumDescription(Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());
    
        DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
    
        if (attributes.Length > 0)
            return attributes[0].Description;
        return value.ToString();
    }
    
    public class EnumDescription
    {
        public string Type { get; set; }
        public IDictionary ValueDescriptions { get; set; }
    }
    

提交回复
热议问题