C# int、Int32 和枚举

发布于 2024-08-13 05:23:04 字数 253 浏览 11 评论 0原文

如果 intInt32 同义,为什么

enum MyEnum : Int32
{
    Value = 1
}

......无法编译? ?

enum MyEnum : int
{
    Value = 1
}

即使将光标悬停在 int 单词上也会显示 struct System.Int32 吗

If int is synonymous to Int32 why does

enum MyEnum : Int32
{
    Value = 1
}

...not compile? Where as

enum MyEnum : int
{
    Value = 1
}

will, even though hovering the cursor over the int word will display struct System.Int32?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

这样的小城市 2024-08-20 05:23:04

底层类型确实是相同的,但编译器依赖于该类型作为确切的别名。这是基于解析的编译错误。我查看了 C# 语法规范以及基于别名定义为标记的底层类型(例如“int”、“unit”...等)。解析器需要来自integral-types语法规则的特定字符串。

该错误是一个解析错误,即使 enum Enum : intenum Enum : Int32 的含义相同。

我不知道对解析步骤强制执行此限制的原因,但我可以尝试猜测:由于 Int32 不是关键字,因此它可能引用实际 int 结构之外的其他内容。如果解析器必须知道类型才能为每个基本类型构建不同的 AST ,那么它不能取决于不是关键字的标记。

尽管 C# 规范将 int 关键字定义为显式别名 System.Int32,但在解析步骤中获取有关显式类型 (Int32) 的信息仍然是一个问题,因为它需要大量在此步骤无法推断的上下文信息。

The underlying type is indeed the same, but the compiler depends on the type to be as the exact alias. This is a compilation error based on parsing. I took a look at C# grammar specification and the underlying types defined there as tokens based on the alias (e.g. 'int', 'unit'... etc.). The parser expects specific strings from the integral-types grammar rule.

The error is a parsing error even though both enum Enum : int means the same as enum Enum : Int32.

I don't know the reason for forcing this limit to parsing step, but I can try guessing: Since Int32 is not a keyword it might refer to something other the actual int struct. If the parser has to know the type in order to build different AST for each base type then it cannot depend on token which is not a keyword.

Even though the C# specification defines the int keyword as explicit alias System.Int32, it's still a problem to get this information about the explicit type (Int32) during parsing step since it requires a lot of context information which cannot be inferred at this step.

醉南桥 2024-08-20 05:23:04

一种熟悉的好奇心......语言规范指出(14.1):

枚举声明可以显式声明底层类型:byte、sbyte、short、ushort、int、uint、long 或 ulong。请注意,char 不能用作基础类型。未显式声明基础类型的枚举声明的基础类型为 int。

但由于 int 通常只是 System.Int32 的别名,所以这并不是不合理 认为两者都可能有效...但实际上并没有。这通常不是一个大问题,但仍然很有趣。

A familiar curiosity... the language spec states (14.1):

An enum declaration may explicitly declare an underlying type of byte, sbyte, short, ushort, int, uint, long or ulong. Note that char cannot be used as an underlying type. An enum declaration that does not explicitly declare an underlying type has an underlying type of int.

But since int is generally just an alias for System.Int32 it isn't unreasonable to think either might work... but indeed it doesn't. It isn't generally a big problem, but intriguing none the less.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文