我有枚举:

public enum Operation {
    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("01")]
    Item01,

    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("02")]
    Item02,

    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("03")]
    Item03,

    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("04")]
    Item04,
}

如何获得XmlEnumAttribute值?

我正在尝试:
var res = Operation.Item1;
var result = (res.GetType().GetField("Item01").GetCustomAttributes(typeof(XmlEnumAttribute), true)[0] as XmlEnumAttribute).Name;

可能存在更好的方法?

最佳答案

您可以使用此扩展方法创建一个帮助器(静态)类

public static string GetXmlEnumAttributeValueFromEnum<TEnum>(this TEnum value) where TEnum : struct, IConvertible
{
    var enumType = typeof(TEnum);
    if (!enumType.IsEnum) return null;//or string.Empty, or throw exception

    var member = enumType.GetMember(value.ToString()).FirstOrDefault();
    if (member == null) return null;//or string.Empty, or throw exception

    var attribute = member.GetCustomAttributes(false).OfType<XmlEnumAttribute>().FirstOrDefault();
    if (attribute == null) return null;//or string.Empty, or throw exception
    return attribute.Name;
}

用法
var res = Operation.Item1;
var result = res.GetXmlAttributeValueFromEnum();

10-06 12:26