Why are operations between different enum types allowed in another enum declaration but not elsewhere?

前端 未结 4 549
太阳男子
太阳男子 2021-02-12 12:26

The C# compiler allows operations between different enum types in another enum type declaration, like this:

public enum VerticalAnchors
{
    Top=1,
    Mid=2,
          


        
4条回答
  •  一向
    一向 (楼主)
    2021-02-12 12:47

    Interesting. You can also ask why this is allowed:

    enum MyType
    {
      Member = DayOfWeek.Thursday | StringComparison.CurrentCultureIgnoreCase,
    }
    

    when this is not allowed:

    var local = DayOfWeek.Thursday | StringComparison.CurrentCultureIgnoreCase;
    

    The reason seems to be that inside the declaration of an enum, in the enum member initializers, any enum value, even a value of an unrelated enum, is considered to be cast to its underlying type. So the compiler sees the above example as:

    enum MyType
    {
      Member = (int)(DayOfWeek.Thursday) | (int)(StringComparison.CurrentCultureIgnoreCase),
    }
    

    I find this very strange. I knew that you could use values of the same enum directly (without stating the cast to the underlying type), as in the last line of:

    enum SomeType
    {
      Read = 1,
      Write = 2,
      ReadWrite = Read | Write,
    }
    

    but I find it very surprising that other enums' members are also cast to their underlying integer types.

提交回复
热议问题