value
参数的EnumMember
属性是有序列化。不显示目的。见MSDN Documentation。
要获得该值,您必须将其序列化,然后解析XML。
另一种方式是写自己的辅助方法,并利用C#内置DescriptionAttribute
:
public enum PaymentCurrency
{
[DescriptionAttribute("CA$")]
CAD,
[DescriptionAttribute("US$")]
USD,
EURO
}
然后使用一个EnumUtils
类自己的辅助方法,你可以这样做:
public class EnumUtils
{
public static string stringValueOf(Enum value)
{
var fi = value.GetType().GetField(value.ToString());
var attributes = (DescriptionAttribute[]) fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}
public static object enumValueOf(string value, Type enumType)
{
string[] names = Enum.GetNames(enumType);
foreach (string name in names)
{
if (stringValueOf((Enum)Enum.Parse(enumType, name)).Equals(value))
{
return Enum.Parse(enumType, name);
}
}
throw new ArgumentException("The string is not a description or value of the specified enum.");
}
}