C# int, Int32 and enums

后端 未结 2 1105
无人共我
无人共我 2020-11-27 17:37

If int is synonymous to Int32 why does

enum MyEnum : Int32
{
    Value = 1
}

...not compile? Where as

         


        
2条回答
  •  一个人的身影
    2020-11-27 18:16

    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.

提交回复
热议问题