Getting attributes of Enum's value

后端 未结 25 2550
慢半拍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:28

    For some programmer humor, a one liner as a joke:

    public static string GetDescription(this Enum value) => value.GetType().GetMember(value.ToString()).First().GetCustomAttribute() is DescriptionAttribute attribute ? attribute.Description : string.Empty;
    

    In a more readable form:

    using System;
    using System.ComponentModel;
    using System.Linq;
    using System.Reflection;
    
    public static class EnumExtensions
    {
        // get description from enum:
    
        public static string GetDescription(this Enum value)
        {
            return value.GetType().
                GetMember(value.ToString()).
                First().
                GetCustomAttribute() is DescriptionAttribute attribute
                ? attribute.Description
                : throw new Exception($"Enum member '{value.GetType()}.{value}' doesn't have a [DescriptionAttribute]!");
        }
    
        // get enum from description:
    
        public static T GetEnum(this string description) where T : Enum
        {
            foreach (FieldInfo fieldInfo in typeof(T).GetFields())
            {
                if (fieldInfo.GetCustomAttribute() is DescriptionAttribute attribute && attribute.Description == description)
                    return (T)fieldInfo.GetRawConstantValue();
            }
    
            throw new Exception($"Enum '{typeof(T)}' doesn't have a member with a [DescriptionAttribute('{description}')]!");
        }
    }
    

提交回复
热议问题