C# ulong 上溢/下溢以某种方式允许

Sle*_*her 5 c# integer overflow underflow ulong

我对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
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?为什么一些下溢错误被捕获而另一些则没有,甚至不抛出异常?我能检测到这些吗?

我专注于通过下溢获得负数,但是当数字大于最大值并溢出时,我看到了类似的事情。

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

Kei*_*las 5

如果你想抛出下溢(或溢出)异常,试试这个:-

checked
{
    ulong number = 0;
    number = number - 10;
}
Run Code Online (Sandbox Code Playgroud)

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

看官方文档

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