Why should I explicitly surround with “unchecked”?

后端 未结 3 2012
余生分开走
余生分开走 2021-01-17 14:40

Is there anyone able to explain me this strange behavior?

    int i = 0x1234;
    byte b1 = (byte)i;
    byte b2 = (byte)0x1234;         //error: const value         


        
3条回答
  •  甜味超标
    2021-01-17 15:07

    You're tripping over a part of section 7.19 of the C# 4 spec:

    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.

提交回复
热议问题