为什么我可以将0.0分配给枚举值,而不是1.0 [英] Why can I assign 0.0 to enumeration values, but not 1.0

查看:35
本文介绍了为什么我可以将0.0分配给枚举值,而不是1.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Just out of curiosity: why can I assign 0.0 to a variable that is of an enumeration type, but not 1.0? Have a look at the following code:

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 值存在异常?

I thought that conversions between numerical types and enumeration values are only allowed via casts? That is I could write Foo value2 = (Foo) 1.0; so that line 2 in Main can compile. Why is there an exception for the value 0.0 in C#?

推荐答案

这是您可以使用0.0的错误.编译器将所有值为零的常量表达式都隐式地视为正好为0.

It's a bug that you can use 0.0. The compiler implicitly treats all constant expressions with a value of zero as just 0.

现在,对于编译器而言,正确是正确的,它允许根据C#5规范的6.1.3节从0的恒定 int 表达式隐式转换为您的枚举.:

Now, it's correct for the compiler to allow an implicit conversion from a constant int expression of 0 to your enum as per section 6.1.3 of the C# 5 specification:

隐式枚举转换允许将十进制整数数字0转换为任何枚举类型和其基础类型为枚举类型的任何可为空的类型.在后一种情况下,通过转换为基础枚举类型并包装结果来评估转换(第4.1.10节).

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)删除为枚举值,但不幸的是我收集到它破坏了太多的代码-即使一开始就不应该允许它.

I've spoken with the C# team about this before: they'd have liked to have removed the accidental conversion from 0.0 (and indeed 0.0m and 0.0f) to enum values, but unfortunately I gather it broke too much code - even though it should never have been allowed in the first place.

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

The Mono mcs compiler prohibits all of these floating point conversions, although it does allow:

const int Zero = 0;
...

SomeEnum x = Zero;

尽管 Zero 是一个常量表达式,但不是是十进制整数的事实.

despite the fact that Zero is a constant expression but not a decimal-integer-literal.

我将来看到C#规范更改以允许任何值为0的整数常量表达式(即模拟 mcs )不会感到惊讶,但是我不希望这样.浮点转换到官方都是正确的.(当然,在预测C#的未来之前,我错了.)

I wouldn't be surprised to see the C# specification change in the future to allow any integer constant expression with a value of 0 (i.e. to mimic mcs), but I wouldn't expect the floating point conversions to ever officially be correct. (I've been wrong before about predicting the future of C#, of course...)

这篇关于为什么我可以将0.0分配给枚举值,而不是1.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆