列挙型とDescriptionAttribute
:を使用してみてください。
public enum REASON_CODES
{
[Description("10")]
HumanReadableReason1,
[Description("11")]
SomethingThatWouldMakeSense,
/* etc. */
}
次に、ヘルパー ( などEnumerations.GetDescription
) を使用して、「実際の」値を取得できます (C# の命名制約内にとどまります)。
それを完全な答えにするために:
これら 2 つのポスターを組み合わせた拡張機能クラスが必要な場合に備えて、次のようにします。
public static class EnumExtensions
{
public static String ToDescription<TEnum>(this TEnum e) where TEnum : struct
{
var type = typeof(TEnum);
if (!type.IsEnum) throw new InvalidOperationException("type must be an enum");
var memInfo = type.GetMember(e.ToString());
if (memInfo != null & memInfo.Length > 0)
{
var descAttr = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (descAttr != null && descAttr.Length > 0)
{
return ((DescriptionAttribute)descAttr[0]).Description;
}
}
return e.ToString();
}
public static TEnum ToEnum<TEnum>(this String description) where TEnum : struct
{
var type = typeof(TEnum);
if (!type.IsEnum) throw new InvalidOperationException("type must be an enum");
foreach (var field in type.GetFields())
{
var descAttr = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (descAttr != null && descAttr.Length > 0)
{
if (((DescriptionAttribute)descAttr[0]).Description == description)
{
return (TEnum)field.GetValue(null);
}
}
else if (field.Name == description)
{
return (TEnum)field.GetValue(null);
}
}
return default(TEnum); // or throw new Exception();
}
}
それで:
public enum CODES
{
[Description("11")]
Success,
[Description("22")]
Warning,
[Description("33")]
Error
}
// to enum
String response = "22";
CODES responseAsEnum = response.ToEnum<CODES>(); // CODES.Warning
// from enum
CODES status = CODES.Success;
String statusAsString = status.ToDescription(); // "11"