为什么选择枚举接受隐式转换为0但不是任何其他整数? [英] Why switch for enum accepts implicit conversion to 0 but no for any other integer?
本文介绍了为什么选择枚举接受隐式转换为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
?
推荐答案
13.1.3隐式枚举转换
13.1.3 Implicit enumeration conversions
隐式枚举转换允许十进制整数字符
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.
分配其他值新版本的枚举,或更改$ b $新版本的枚举成员的b值可能会导致
相关源代码的问题。通常,在switch语句中使用枚举值是
,如果额外的元素已添加
到枚举类型,则默认值的测试可能会意外返回true
。
这篇关于为什么选择枚举接受隐式转换为0但不是任何其他整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文