为什么我应该明确地用“未选中”? [英] Why should I explicitly surround with "unchecked"?
问题描述
有没有人能够解释这个奇怪的行为?
Is there anyone able to explain me this strange behavior?
int i = 0x1234;
byte b1 = (byte)i;
byte b2 = (byte)0x1234; //error: const value '4660' can't convert to byte (use unchecked)
byte b3 = unchecked((byte)0x1234);
byte b4 = checked((byte)i); //throws
byte b5 = (byte)(int)0x1234; //error: same as above
注意:这是一个空的控制台应用程序, / em>启用算术检查(默认为)。
预先感谢大家。
NOTE: It's an empty Console application, with NO arithmetic checking enabled (as default is). Thank you everybody in advance.
编辑:我应该很清楚,但不是所有。
I supposed to be clear enough, but not for all.
我知道一个字不能放入一个字节。但是,默认情况下,C#程序允许某些危险操作,主要是出于性能原因。
I do know that a word can't fit into a byte. But, by default, a C# program allows certain "dangerous" operations, primarily for performance reason.
同样,我可以将两个大整数加在一起, 。
Similarly, I may sum two large integers together and having no overflow at all.
我很奇怪上面的编译时错误:b1转换/赋值是编译的,b2不能编译。显然没有什么区别,因为两者都是Int32有相同的价值。
My wonder was about the compile-time error above: the b1 cast/assignment is compiled, the b2 can't compile. Apparently there's no difference, because both are Int32 having the same value.
希望现在很清楚。
推荐答案
您跳过C#4规范第7.19节的一部分:
You're tripping over a part of section 7.19 of the C# 4 spec:
表达式显式地放置在
未检查的
上下文中,在表达式的编译期评估期间发生在积分型算术运算和转换中的溢出总是导致编译时错误。 / p>
Unless a constant expression is explicitly placed in an
unchecked
context, overflows that occur in integral-type arithmetic operations and conversions during the compile-time evaluation of the expression always cause compile-time errors.
基本上,关键是即使你愿意允许操作在执行时溢出,如果您尝试使用在编译时无法转换为目标类型的常量表达式 ,您必须告诉编译器您确实知道您在做什么。
Basically, the point is that even if you're happy to allow operations to overflow at execution time, if you're trying to use a constant expression which can't be converted to the target type at compile time, you have to tell the compiler that you really know what you're doing.
例如,在这种情况下,您将丢失信息 - 它将等同于
For example, in this case you're losing information - it'll be equivalent to
byte b3 = 0x34;
所以你通常你更清晰的代码,不会误导读者。这是相对罕见的,你想溢出在一个常数 - 大部分时间,你应该指定有效的值。
so you'd normally be better off just specifying that, to give you clearer code which doesn't mislead the reader. It's relatively rare that you want to overflow in a constant - most of the time you should just specify the valid value instead.
这篇关于为什么我应该明确地用“未选中”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!