本文介绍了从枚举获取XmlEnumAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有枚举:
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值
How I can get XmlEnumAttribute value?
我想在那?
var res = Operation.Item1;
var result = (res.GetType().GetField("Item01").GetCustomAttributes(typeof(XmlEnumAttribute), true)[0] as XmlEnumAttribute).Name;
可能存在更好的方法?
May be exists better method?
推荐答案
您可以创建一个帮手(静态)类,这种扩展方法
You could create an helper (static) class, with this extension method
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;
}
使用
usage
var res = Operation.Item1;
var result = res.GetXmlAttributeValueFromEnum();
这篇关于从枚举获取XmlEnumAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!