c# – 为什么选择枚举接受隐式转换为0但不是任何其他整数?

有一个:

enum SomeEnum
{
    A = 0,
    B = 1,
    C = 2
}

现在编译器允许我写:

SomeEnum x = SomeEnum.A;
switch(x)
{
    case 0: // <--- Considered SomeEnum.A
        break;
    case SomeEnum.B:
        break;
    case SomeEnum.C:
        break;
    default:
        break;
}

0被认为是SomeItems.A。但我不能写:

SomeEnum x = SomeEnum.A;
switch(x)
{
    case 0:
        break;
    case 1: // <--- Here is a compilation error.
        break;
    case SomeEnum.C:
        break;
    default:
        break;
}

为什么只有隐式转换存在0?

ECMA-334 (C# Language Specification)

13.1.3 Implicit enumeration conversions

An implicit enumeration conversion permits the decimal-integer-literal
0 to be converted to any enum-type.

enum’s默认值为0,在编译时已知这是在switch语句中允许的原因。对于0以外的值,在编译时无法确定此值是否存在于枚举中。

enum (C# Reference)

Assigning additional values new versions of enums, or changing the
values of the enum members in a new version, can cause problems for
dependant source code. It is often the case that enum values are
used in switch statements, and if additional elements have been added
to the enum type, the test for default values can return true
unexpectedly.

http://stackoverflow.com/questions/14950750/why-switch-for-enum-accepts-implicit-conversion-to-0-but-no-for-any-other-intege

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c# – 为什么选择枚举接受隐式转换为0但不是任何其他整数?