【发布时间】:2014-01-07 21:53:40
【问题描述】:
我在将任意数字转换为字节的方法中有以下代码:
try {
return (byte) Convert.ChangeType(operand.RealValue, TypeCode.Byte);
}
catch (OverflowException) {
if (AllowArithmeticOverflow) {
unchecked {
decimal d = Convert.ToDecimal(operand.RealValue);
return (byte) d;
}
}
throw;
}
在此代码中,operand.RealValue 应为任意数字。对于我正在测试的示例,它是一个 sbyte,其值为 -13(已通过调试器验证)。我可以在调试器中单步执行并到达return (byte) d; 行...此时会引发OverflowException,尽管它位于unchecked 块中。
那么...是什么给了?
另外,如果您正在查看我的实现并想知道我到底在做什么 - 这是我迄今为止尝试过的所有体操的结果,没有得到这个例外。必须简洁的答案获胜:)
注意:异常信息如下:
System.OverflowException:值太大或太小 一个无符号字节。 ---> System.OverflowException: 值也是 对于 UInt32 来说太大或太小。
【问题讨论】:
-
-13 对于无符号字节来说太小了
-
是的,很明显 - 但我还是想允许这样做,基本上只是 reinterpret_cast 它......
-
@SwDevMan81 赢了!再简洁不过了。
-
那么-13应该对应什么字节值呢? 242? 115? 0?
-
但原因是因为unchecked是用于算术运算和转换:
The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions.