属性のvalue
引数はシリアル化のためにあります。EnumMember
表示目的ではありません。MSDN ドキュメントを参照してください。
その値を取得するには、シリアル化してから XML を解析する必要があります。
もう 1 つの方法は、独自のヘルパー メソッドを作成し、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.");
}
}