6

我对这种ulong类型的行为有点困惑。我理解它是一个64 位整数,用于正数(最大值 18,446,744,073,709,551,615)。我刚开始使用它是因为我需要非常大的正数,但是围绕潜在的负数有一些我不理解的奇怪行为。

ulong big = 1000000;    //Perfectly legal

ulong negative = -1;    //"Constant value "-1" cannot be converted to a ulong" Makes sense


//Attempt to sneak around the -1 as a constant compile-time error
int negativeInt = -1;
ulong negativeUlongFail = negativeInt;    //"Cannot implicitly convert 'int' to 'ulong'.
                                 //An explicit conversion exists (are you missing a cast?)"
//So I add casting
ulong negativeUlong = (ulong)negativeInt;    //But this yields 18446744073709551615

//Try and get a negative number indirectly
ulong number = 0;
number = number - 10;  //now number is 18446744073709551615 but no underflow error

这是怎么回事?为什么一些下溢错误被捕获而其他错误甚至不抛出异常?我可以检测到这些吗?

我专注于通过下溢来获得负数,但是在获得大于最大值和上溢的数字时,我也看到过类似的情况。

我不确定它们在技术上是错误还是异常,所以如果我使用了不正确的术语,请原谅我

4

1 回答 1

5

如果您希望抛出下溢(或溢出)异常,请尝试以下操作:-

checked
{
    ulong number = 0;
    number = number - 10;
}

默认情况下,异常被吞没(它在未经检查的情况下运行)。

见官方文档

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/checked

于 2017-07-23T23:35:04.407 回答