允许使用以数字开头的Enum成员名



我正试图建立一个enum来容纳钣金表(厚度)。我想如果我能写:

using System.ComponentModel;
public enum Gauge
{
    [Description("24 Gauge")]
    24Ga = 239,
    [Description("20 Gauge")]
    20Ga = 359,
    [Description("18 Gauge")]
    18Ga = 478,
    [Description("16 Gauge")]
    16Ga = 598,
    [Description("14 Gauge")]
    14Ga = 747
}

但是被Visual Studio拒绝。

可以这样:

using System.ComponentModel;
public enum Gauge
{
    [Description("24 Gauge")]
    G24 = 239,
    [Description("20 Gauge")]
    G20 = 359,
    [Description("18 Gauge")]
    G18 = 478,
    [Description("16 Gauge")]
    G16 = 598,
    [Description("14 Gauge")]
    G14 = 747
}

这使得不允许以数字字符开头的Enum成员名看起来非常明显,尽管变量名通常允许这样做。

我的问题是:这个限制在哪里指定?Enum类文档似乎没有提到它。

No。枚举成员必须是有效的标识符。来自c# 5规范第14.3节:

枚举类型声明的体定义了零个或多个枚举成员,这些成员是枚举类型的命名常量。不能有两个枚举成员具有相同的名称。

enum-member-declarations:
<代码> enum-member-declaration
枚举成员声明枚举成员声明
enum-member-declaration:
<代码><子>属性选择标识符
attributesoptidentifier CC_5 constant-expression

…第2.4.2节描述了标识符:

标识符:
<代码> available-identifier
CC_7 identifier-or-keyword
available-identifier:
不是关键字
标识符或关键字 identifier-or-keyword:
<代码> identifier-start-character identifier-part-characters <子>选择
identifier-start-character:
<代码>字母
=1(下划线U+005F)

注意数字不是,而是标识符-start-character

是否允许有以数字开头的Enum成员名?

不,语言语法不允许。

参见2.4.2标识符

identifier-start-character:
    letter-character
    _ (the underscore character U+005F) 

最新更新