本文介绍了C#乘以值int.MaxValue的两个变量不会导致发生OverflowException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个整数阵列,包含两个值,每个INT32的最大值:
I've got an integer array that contains two values, each the maximum value of int32:
int[] factors = new int[] { 2147483647, 2147483647 };
我的尝试的得到这两个数字的产品创造一个发生OverflowException:
I'm trying to get the product of these two numbers to create an OverflowException:
try
{
int product = factors[0] * factors [1];
}
catch(Exception ex)
{
}
出乎我的意料(和沮丧),产品实际上返回值为1。这是为什么,我怎么会去当两个整数的乘积超过int.MaxValue?
Much to my surprise (and dismay), product actually returns a value of 1. Why is this, and how would I go about throwing an exception when the product of two integers exceeds int.MaxValue?
推荐答案
由于C#的默认行为是不符合INT检查溢出。
但是,您可以通过使用关键字。
Because the default behavior of C# is not to check overflow with int.However, you can force overflow checking by using checked
keyword.
try
{
checked
{
int product = factors[0] * factors [1];
}
}
catch(Exception ex)
{
}
这篇关于C#乘以值int.MaxValue的两个变量不会导致发生OverflowException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!