任何人都知道最好用什么来读取XmlEnumAttribute
选项1:使用GetMember
public static string XmlEnum(this Enum e)
{
Type type = e.GetType();
MemberInfo[] memInfo = type.GetMember(e.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(XmlEnumAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((XmlEnumAttribute)attrs[0]).Name;
}
}
return e.ToString();
}
Run Code Online (Sandbox Code Playgroud)
选项2:使用GetField
public static string XmlEnum2(this Enum e)
{
Type type = e.GetType();
FieldInfo info = type.GetField(e.ToString());
if (!info.IsDefined(typeof(XmlEnumAttribute), false))
{
return e.ToString();
}
object[] attrs = info.GetCustomAttributes(typeof(XmlEnumAttribute), false);
return ((XmlEnumAttribute)attrs[0]).Name;
}
Run Code Online (Sandbox Code Playgroud)