Cap*_*awk 1 c# enums attributes
我需要将以下代码放入枚举中:
10, 11, 13, AA, BB, EE
Run Code Online (Sandbox Code Playgroud)
我正在努力让他们进入C#中的枚举.我目前有这个:
public enum REASON_CODES { _10, _11, _13, AA, BB, CC }
Run Code Online (Sandbox Code Playgroud)
但想拥有这个,数字被识别为字符串,而不是整数:
public enum REASON_CODES { 10, 11, 13, AA, BB, CC }
Run Code Online (Sandbox Code Playgroud)
这可能还是我在做梦?
尝试使用枚举和DescriptionAttribute:
public enum REASON_CODES
{
[Description("10")]
HumanReadableReason1,
[Description("11")]
SomethingThatWouldMakeSense,
/* etc. */
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用一个帮助器(比如Enumerations.GetDescription)获得"真实"值(同时保持在C#命名约束内).
为了使它成为一个完整的答案:
万一有人想要一个与这两张海报结婚的扩展课:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后:
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"
Run Code Online (Sandbox Code Playgroud)