处理整数溢出是一项常见任务,但在C#中处理它的最佳方法是什么?是否有一些语法糖可以使其比其他语言更简单?还是这确实是最好的方法?
int x = foo();
int test = x * common;
if(test / common != x)
Console.WriteLine("oh noes!");
else
Console.WriteLine("safe!");
处理整数溢出是一项常见任务,但在C#中处理它的最佳方法是什么?是否有一些语法糖可以使其比其他语言更简单?还是这确实是最好的方法?
int x = foo();
int test = x * common;
if(test / common != x)
Console.WriteLine("oh noes!");
else
Console.WriteLine("safe!");
我很少需要使用这个功能,但您可以使用checked关键字:
int x = foo();
int test = checked(x * common);
尝试以下操作
int x = foo();
try {
int test = checked (x * common);
Console.WriteLine("safe!");
} catch (OverflowException) {
Console.WriteLine("oh noes!");
}
最好的方法是像Michael所说的那样 - 使用Checked关键字。 可以这样做:
int x = int.MaxValue;
try
{
checked
{
int test = x * 2;
Console.WriteLine("No Overflow!");
}
}
catch (OverflowException ex)
{
Console.WriteLine("Overflow Exception caught as: " + ex.ToString());
}
int x = foo();
if ((x * common) / common != x)
Console.WriteLine("oh noes!");
else
Console.WriteLine("safe!");
x
,因为调用foo()
三次是愚蠢的。虽然这个帖子比较老,但我最近遇到了同样的问题。我不想使用异常机制。最终我采用了以下方法:
long a = (long)b * (long)c;
if(a>int.MaxValue || a<int.MinValue)
do whatever you want with the overflow
return((int)a);
int.MaxValue + 1
会给你-2147483648或int.MinValue
。所以a
永远不能比MaxValue更大或比MinValue更小。把数字想象成一条线,就像这样:-2147483648,-2147483647,... 0 ... 2147483646,2147483647
,当你超过最大值时,它会回流到最小值。 - Ray Cheng所以,我在事后才遇到了这个问题,它基本上回答了我的问题,但对于我的特定情况(如果有其他人有相同的要求),我希望任何超出有符号整数正值的内容都能够被设定为int.MaxValue
:
int x = int.MaxValue - 3;
int someval = foo();
try
{
x += someval;
}
catch (OverflowException)
{
x = int.MaxValue;
}
/checked
编译选项或使用checked
关键字,否则异常不会被抛出,对吗? - Paul Knopf