使用数字在枚举C#
希望一个quicky。
Hopefully a quicky.
这是一个有效的枚举
public enum myEnum
{
a= 1,
b= 2,
c= 3,
d= 4,
e= 5,
f= 6,
g= 7,
h= 0xff
};
但是,这不是
public enum myEnum
{
1a = 1,
2a = 2,
3a = 3,
};
有没有一种方法,我可以在一个枚举使用一个号码。我已经有code填充从枚举下拉列表所以这将是非常方便的。
Is there a way I can use an number in a enum. I already have code to populate dropdowns from enums so it would be quite handy
没有标识都在C#中可以用一个数字(词法/语法分析原因)开始。考虑增加一个[说明]属性的枚举值:
No identifier at all in C# may begin with a number (for lexical/parsing reasons). Consider adding a [Description] attribute to your enum values:
public enum myEnum
{
[Description("1A")]
OneA = 1,
[Description("2A")]
TwoA = 2,
[Description("3A")]
ThreeA = 3,
};
然后你可以从这样的一个枚举值获得的描述:
Then you can get the description from an enum value like this:
((DescriptionAttribute)Attribute.GetCustomAttribute(
typeof(myEnum).GetFields(BindingFlags.Public | BindingFlags.Static)
.Single(x => (myEnum)x.GetValue(null) == enumValue),
typeof(DescriptionAttribute))).Description
基于XSA的评论
下面,我想在一个如何使这个更具可读性扩大。最简单的,你可以只创建一个静态(扩展)方法:
Based on XSA's comment below, I wanted to expand on how one could make this more readable. Most simply, you could just create a static (extension) method:
public static string GetDescription(this Enum value)
{
return ((DescriptionAttribute)Attribute.GetCustomAttribute(
value.GetType().GetFields(BindingFlags.Public | BindingFlags.Static)
.Single(x => x.GetValue(null).Equals(value)),
typeof(DescriptionAttribute)))?.Description ?? value.ToString();
}
这取决于你是否要让它的扩展方法,并在上面的实施,我将它退回到枚举的正常名称,如果没有 [DescriptionAttribute]
已提供。
现在,您可以通过获得描述一个枚举值:
Now you can get the description for an enum value via:
myEnum.OneA.GetDescription()