C#INT,的Int32和枚举INT

2023-09-02 21:08:11 作者:相思渺无畔

如果 INT 的代名词到的Int32 为什么

enum MyEnum : Int32
{
    Value = 1
}

...无法编译?凡为

...not compile? Where as

enum MyEnum : int
{
    Value = 1
}

意志,即使当光标在INT字会显示结构System.Int32的?

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

推荐答案

基础类型确实是相同的,但是编译器取决于类型是一样的确切别名。这是一种基于解析编译错误。我把那里定义为标记的基本类型看看C#语法规范,并根据别名(如INT,单位......等)。解析器期望特定字符串从整数类型的语法规则。

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.

的错误是分析错误即使两个枚举枚举:INT 意思是一样的枚举枚举:的Int32

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

我不知道强迫此限制以分析步骤的原因,但我可以尝试猜测:由于的Int32不是一个关键字它可能是指其他的东西实际INT结构。如果解析器已经知道,以建立不同 AST ,了解各个基本类型的类型,那么就可以不依赖令牌而不是关键字

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.

尽管C#规范定义的 INT 的关键字作为明确的别名的 System.Int32的的,它仍然是一个问题,以获取有关显式类型(Int32)在分析过程中该信息因为它步骤需要大量的这不能在这个步骤被推断的上下文信息。

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.