【问题标题】:Is is allowed to have an Enum member name that start with a number? [duplicate]是否允许有一个以数字开头的 Enum 成员名称? [复制]
【发布时间】:2014-08-08 20:24:44
【问题描述】:

我正在尝试设置一个枚举来保存钣金量规(厚度)。我想如果我能写出来会是最直观的:

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 Class documentation 似乎没有提到它。

【问题讨论】:

  • "[...] 十进制类型。它不是一个 64 位整数,小数位在后台移动吗?" 在@987654322 中阅读它@,请...
  • @gunr2171 拍摄,我想回滚这些更改,因为我将第二部分转移到了一个新问题,但我似乎无法做到这一点。请版主回滚对此的更改。 . .
  • 我曾经在其他语言的那个位置使用数字,但现在我认为这是一个愚蠢的问题。
  • "尽管变量名通常允许这样做。" 不,不是。

标签: c# enums


【解决方案1】:

没有。枚举成员必须是有效的标识符。来自C# 5 specification 的第 14.3 节:

枚举类型声明的主体定义了零个或多个枚举成员,它们是枚举类型的命名常量。没有两个枚举成员可以具有相同的名称。

枚举成员声明:
<em>枚举成员声明</em><br>枚举成员声明 em> , 枚举成员声明
枚举成员声明:
<em>属性<sub>opt</sub><em>标识符</em><br>属性opt 标识符 = 常量表达式

...和标识符在第 2.4.2 节中描述:

标识符:
<em>available-identifier</em><br>@标识符或关键字
available-identifier:
An <em>identifier-or-keyword</em> 不是<em>关键字</em><br><em>identifier-or -keyword:</em><br>identifier-start-character identifier-part-charactersopt
标识符开始字符:
<em>字母字符</em><br>_(下划线字符 U+005F)

注意一个数字如何不是一个标识符开始字符​​em>。

【讨论】:

    【解决方案2】:

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

    不,语言语法不允许。

    2.4.2 Identifiers

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多