希望快点.
这是一个有效的枚举
public enum myEnum
{
a= 1,
b= 2,
c= 3,
d= 4,
e= 5,
f= 6,
g= 7,
h= 0xff
};
Run Code Online (Sandbox Code Playgroud)
但事实并非如此
public enum myEnum
{
1a = 1,
2a = 2,
3a = 3,
};
Run Code Online (Sandbox Code Playgroud)
有没有办法可以在枚举中使用数字.我已经有了代码来填充枚举下拉列表,所以它会非常方便
Kir*_*oll 74
C#中根本没有标识符可以以数字开头(出于词汇/解析的原因).考虑在枚举值中添加[Description]属性:
public enum myEnum
{
[Description("1A")]
OneA = 1,
[Description("2A")]
TwoA = 2,
[Description("3A")]
ThreeA = 3,
};
Run Code Online (Sandbox Code Playgroud)
然后你可以从这样的枚举值中获取描述:
((DescriptionAttribute)Attribute.GetCustomAttribute(
typeof(myEnum).GetFields(BindingFlags.Public | BindingFlags.Static)
.Single(x => (myEnum)x.GetValue(null) == enumValue),
typeof(DescriptionAttribute))).Description
Run Code Online (Sandbox Code Playgroud)
根据XSA在下面的评论,我想扩展一下如何让它更具可读性.最简单的说,你可以创建一个静态(扩展)方法:
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();
}
Run Code Online (Sandbox Code Playgroud)
您是否想要将其作为扩展方法取决于您,并且在上面的实现中,如果没有[DescriptionAttribute]提供,我已经使它回退到枚举的正常名称.
现在,您可以通过以下方式获取枚举值的描述:
myEnum.OneA.GetDescription()
Run Code Online (Sandbox Code Playgroud)
C#(和大多数语言)中的标识符不能以数字开头.
如果您可以使用枚举名称修改填充下拉列表的代码,则可能有一个hack在填充下拉列表时删除前导下划线并定义您的枚举,如下所示:
public enum myEnum
{
_1a = 1,
_2a = 2,
_3a = 3
};
Run Code Online (Sandbox Code Playgroud)
或者如果你不喜欢下划线,你可以想出你自己的'前缀被剥离'方案(可能将前缀传递给构造函数或方法,它将填充枚举中的下拉列表).
简短明快的 4 行代码。
我们简单地使用枚举作为代码中项目的命名整数,
所以任何最简单的方法都可以。
public enum myEnum
{
_1 = 1,
_2,
_3,
};
Run Code Online (Sandbox Code Playgroud)
同样对于十进制值,
public enum myEnum
{
_1_5 = 1,
_2_5,
_3_5,
};
Run Code Online (Sandbox Code Playgroud)
因此,在代码中使用它时,
int i = cmb1.SelectedIndex(0); // not readable
int i = cmb1.SelectedIndex( (int) myEnum._1_5); // readable
Run Code Online (Sandbox Code Playgroud)