gpt4 book ai didi

c# - 为什么我可以将 0.0 分配给枚举值,而不是 1.0

转载 作者:IT王子 更新时间:2023-10-29 03:37:40 26 4
gpt4 key购买 nike

只是出于好奇:为什么我可以将 0.0 分配给枚举类型的变量,而不是 1.0?看看下面的代码:

public enum Foo
{
Bar,
Baz
}

class Program
{
static void Main()
{
Foo value1 = 0.0;
Foo value2 = 1.0; // This line does not compile
Foo value3 = 4.2; // This line does not compile
}
}

我以为数值类型和枚举值之间的转换只能通过强制转换来实现?也就是说,我可以编写 Foo value2 = (Foo) 1.0; 以便 Main 中的第 2 行可以编译。为什么 C# 中的值 0.0 会出现异常?

最佳答案

这是一个错误,你可以使用 0.0.编译器隐式地将所有值为零的常量表达式视为 0。

现在,根据 C# 5 规范的第 6.1.3 节,编译器允许从 0 的常量 int 表达式隐式转换为您的枚举是正确的 :

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).

我之前与 C# 团队讨论过这个问题:他们希望删除从 0.0(实际上是 0.0m 和 0.0f)到枚举值的意外转换,但不幸的是我收集到它破坏了太多代码 - 尽管它一开始就不应该被允许。

Mono mcs 编译器禁止所有这些浮点转换,尽管它确实允许:

const int Zero = 0;
...

SomeEnum x = Zero;

尽管 Zero 是常量表达式,但不是十进制整数。

如果将来 C# 规范发生变化以允许任何值为 0 的整数常量表达式(即模仿 mcs),我不会感到惊讶,但我不希望到永远的浮点转换官方是正确的。 (当然,我之前对 C# 的 future 的预测是错误的……)

关于c# - 为什么我可以将 0.0 分配给枚举值,而不是 1.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23762475/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com