Why switch for enum accepts implicit conversion to 0 but no for any other integer?(为什么 switch for enum 接受隐式转换为 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.
这篇关于为什么 switch for enum 接受隐式转换为 0 但不接受任何其他整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 switch for enum 接受隐式转换为 0 但不接受任何其他整数?


- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01