Getting attributes of Enum's value

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

    This extension method will obtain a string representation of an enum value using its XmlEnumAttribute. If no XmlEnumAttribute is present, it falls back to enum.ToString().

    public static string ToStringUsingXmlEnumAttribute(this T enumValue)
        where T: struct, IConvertible
    {
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException("T must be an enumerated type");
        }
    
        string name;
    
        var type = typeof(T);
    
        var memInfo = type.GetMember(enumValue.ToString());
    
        if (memInfo.Length == 1)
        {
            var attributes = memInfo[0].GetCustomAttributes(typeof(System.Xml.Serialization.XmlEnumAttribute), false);
    
            if (attributes.Length == 1)
            {
                name = ((System.Xml.Serialization.XmlEnumAttribute)attributes[0]).Name;
            }
            else
            {
                name = enumValue.ToString();
            }
        }
        else
        {
            name = enumValue.ToString();
        }
    
        return name;
    }
    

提交回复
热议问题