【发布时间】:2018-10-24 17:01:14
【问题描述】:
我又一次偶然发现了System.Decimal 的怪事并寻求解释。
当将System.Decimal 类型的值转换为其他类型(即System.Int32)时,checked keyword 和-checked compiler option 似乎被忽略了。
我创建了以下测试来演示这种情况:
public class UnitTest
{
[Fact]
public void TestChecked()
{
int max = int.MaxValue;
// Expected if compiled without the -checked compiler option or with -checked-
Assert.Equal(int.MinValue, (int)(1L + max));
// Unexpected
// this would fail
//Assert.Equal(int.MinValue, (int)(1M + max));
// this succeeds
Assert.Throws<OverflowException>(() => { int i = (int)(1M + max); });
// Expected independent of the -checked compiler option as we explicitly set the context
Assert.Equal(int.MinValue, unchecked((int)(1L + max)));
// Unexpected
// this would fail
//Assert.Equal(int.MinValue, unchecked((int)(1M + max)));
// this succeeds
Assert.Throws<OverflowException>(() => { int i = unchecked((int)(1M + max)); });
// Expected independent of the -checked compiler option as we explicitly set the context
Assert.Throws<OverflowException>(() => { int i = checked((int)(1L + max)); });
// Expected independent of the -checked compiler option as we explicitly set the context
Assert.Throws<OverflowException>(() => { int i = checked((int)(1M + max)); });
}
}
我所有的研究单位现在都没有对这种现象做出适当的解释,甚至没有找到一些misinformation claiming that it should work。 我的研究已经包括C# specification
有没有人可以解释一下?
【问题讨论】: