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
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01