C#ulong上溢/下溢以某种方式允许 [英] C# ulong overflow / underflow somehow allowed
问题描述
我对 ulong
类型的行为有些困惑.我了解它是用于64位整数正数(最大值18,446,744,073,709,551,615).我刚开始使用它是因为我需要非常大的正数,但是对于潜在的负数,我不了解某些奇怪的行为.
I'm a little confused about the behavior of the ulong
type. I understand it to be a 64-bit integer used for positive numbers (max value 18,446,744,073,709,551,615). I just started using it because I need really big positive numbers, but there's some strange behavior I don't understand around potential negative numbers.
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
这是怎么回事?如何捕获一些下溢错误,而没有捕获甚至不抛出异常?我可以检测到这些吗?
我专注于通过下溢获得负数,但是当数字大于最大值并发生溢出时,我也看到过类似的事情.
I focused on getting negative numbers by underflowing, but I've seen similar things when getting numbers bigger than the max value and overflowing.
我不确定它们在技术上是错误还是例外,因此如果我使用了错误的术语,请原谅我
推荐答案
如果要引发下溢(或上溢)异常,请尝试以下方法:-
if you want the underflow (or overflow) exception to be thrown, try this instead :-
checked
{
ulong number = 0;
number = number - 10;
}
默认情况下,该异常会被吞下(运行时未经检查).
by default the exception gets swallowed (it runs in unchecked).
请参阅官方文档
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/checked
这篇关于C#ulong上溢/下溢以某种方式允许的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!