Getting attributes of Enum's value

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

    In addition to AdamCrawford response, I've further created a more specialized extension methods that feed of it to get the description.

    public static string GetAttributeDescription(this Enum enumValue)
    {
        var attribute = enumValue.GetAttributeOfType();
        return attribute == null ? String.Empty : attribute.Description;
    } 
    

    hence, to get the description, you could either use the original extension method as

    string desc = myEnumVariable.GetAttributeOfType().Description
    

    or you could simply call the the extension method here as:

    string desc = myEnumVariable.GetAttributeDescription();
    

    Which should hopefully make your code a bit more readable.

提交回复
热议问题