Getting attributes of Enum's value

后端 未结 25 2576
慢半拍i
慢半拍i 2020-11-22 00:35

I would like to know if it is possible to get attributes of the enum values and not of the enum itself? For example, suppose I have the following <

相关标签:
25条回答
  • 2020-11-22 01:29

    I implemented this extension method to get the description from enum values. It works for all kind of enums.

    public static class EnumExtension
    {
        public static string ToDescription(this System.Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return attributes.Length > 0 ? attributes[0].Description : value.ToString();
        }
    }
    
    0 讨论(0)
提交回复
热议问题