Getting attributes of Enum's value

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

    Taking advantage of some of the newer C# language features, you can reduce the line count:

    public static TAttribute GetEnumAttribute(this Enum enumVal) where TAttribute : Attribute
    {
        var memberInfo = enumVal.GetType().GetMember(enumVal.ToString());
        return memberInfo[0].GetCustomAttributes(typeof(TAttribute), false).OfType().FirstOrDefault();
    }
    
    public static string GetEnumDescription(this Enum enumValue) => enumValue.GetEnumAttribute()?.Description ?? enumValue.ToString();
    

提交回复
热议问题