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

前端 未结 4 552
太阳男子
太阳男子 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:53

    It is actually not in the spec as far as I can tell. There is something related:

    If the declaration of the enum member has a constant-expression initializer, the value of that constant expression, implicitly converted to the underlying type of the enum, is the associated value of the enum member.

    Although VerticalAnchors.Top & HorizontalAnchors.Lef has type VerticalAnchors it can be implicitly converted to VisualAnchors. But this does not explain why the constant expression itself supports implicit conversions everywhere.

    Actually, it appears explicitly to be against the spec:

    The compile-time evaluation of constant expressions uses the same rules as run-time evaluation of non-constant expressions, except that where run-time evaluation would have thrown an exception, compile-time evaluation causes a compile-time error to occur.

    If I didn't miss something, the spec not only does not allows this explicitly, it disallows it. Under that assumption it would be a compiler bug.

提交回复
热议问题