为什么 enum 的 switch 接受隐式转换为 0 而不是任何其他整数? [英] Why switch for enum accepts implicit conversion to 0 but no for any other integer?

查看:26
本文介绍了为什么 enum 的 switch 接受隐式转换为 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.但我不会写:

0 is considered SomeItems.A. But I can't write:

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

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

Why only implicit conversion exists for 0?

推荐答案

来自 ECMA-334(C# 语言规范)

13.1.3 隐式枚举转换

隐式枚举转换允许十进制-整数-文字0 转换为任何枚举类型.

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

枚举的默认值为0 并且在编译时就知道这就是 switch 语句中允许它的原因.对于 0 以外的值,编译时无法确定该值是否存在于枚举中.

enum's default value is 0 and at compile time it is known that is why it is allowed in the switch statement. For value other than 0, it can't be determine at compile time whether this value will exist in the enum or not.

枚举(C# 参考)

分配附加值新版本的枚举,或更改新版本中枚举成员的值可能会导致问题依赖源代码.通常的情况是 枚举值是在 switch 语句中使用,如果添加了其他元素对于枚举类型,默认值的测试可以返回true出乎意料.

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.

这篇关于为什么 enum 的 switch 接受隐式转换为 0 而不是任何其他整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆