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

C# ulong overflow / underflow somehow allowed

我对 ulong 类型的行为有点困惑。我理解它是 64-bit integer used for positive numbers(最大值 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

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

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

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

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

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

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

查看官方文档

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