【问题标题】:C# ulong overflow / underflow somehow allowedC# ulong 允许上溢/下溢
【发布时间】:2017-07-23 23:16:52
【问题描述】:

我对@9​​87654322@ 类型的行为有点困惑。我理解它是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

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

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

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

【问题讨论】:

  • 编译器默认开启下溢/下溢检测,运行时不开启。后者是项目设置,Project > Properties > Build tab > Advanced 按钮。打开复选框对于 Debug 配置是一个好主意。对于发布版本而言,检查并不多,检查非常昂贵。使用 checkedunchecked 关键字即时覆盖这些默认值。

标签: c# integer overflow underflow ulong


【解决方案1】:

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

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

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

查看官方文档

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 2011-05-13
    • 1970-01-01
    相关资源
    最近更新 更多