C# 枚举 - 为什么从 0 *隐式* 转换有效?

标签 c# enums compiler-errors

<分区>

拿这段代码:

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/

相关文章:

java - Hibernate 无法保存其中一个字段为枚举的实体

c - 在 C 中查找未使用的枚举成员

c++ - 将 QVariant 中的枚举转换为整数

xcode - 错误 : main. jsbundle 不存在 - React Native 0.60.4

c++ - htmlcxx 编译错误

c - 以下c程序的编译时错误的正确解释是什么

c# - multiple 不是元素 fileupload 的有效属性

c# - 在C#中使用参数委托(delegate)给其他线程

c# - 如何使用 MVVM 在 WPF 中将命令附加到事件 - DataGrid 选择更改为更新显示在 TextBlock 中的行数

c# - 与 Promise.all 等效的 C# 是什么?