<分区>
拿这段代码:
enum En {
val1,
val2,
}
void Main()
{
En plop = 1; //error: Cannot implicitly convert type 'int' to 'En'
En woop = 0; //no error
}
当然,将 1
分配给 enum
类型的变量时会失败。 (拍打一个显式 Actor ,它会工作。)
我的问题是:为什么分配 0 时它不会失败?
<分区>
拿这段代码:
enum En {
val1,
val2,
}
void Main()
{
En plop = 1; //error: Cannot implicitly convert type 'int' to 'En'
En woop = 0; //no error
}
当然,将 1
分配给 enum
类型的变量时会失败。 (拍打一个显式 Actor ,它会工作。)
我的问题是:为什么分配 0 时它不会失败?
最佳答案
是这样的,因为规范是这么说的...
这是为什么给所有枚举一个值为 0 的项目总是一个好主意的另一个原因,因为有时您可能会得到具有该值的它们。
C# 语言规范 6.1.3 中的相应部分:
6.1.3 Implicit enumeration conversions
An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type and to any nullable-type whose underlying type is an enum-type. In the latter case the conversion is evaluated by converting to the underlying enum-type and wrapping the result (§4.1.10).
至于为什么会这样 - 好吧,我猜只有语言委员会中决定这些事情的人知道。
事实上,如果您查看 rawling 对原始问题的评论,我们确实有类似的东西。
关于C# 枚举 - 为什么从 0 *隐式* 转换有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16960428/