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.");
}
}