在最后一行的下面的方法中,我总是得到一个例外:
System.OverflowException: Value was either too large or too small for an Int32.
我无法解释原因,因为我正在明确检查:
private Int32 ConvertValue(double value)
{
if (value > Int32.MaxValue)
{
Console.WriteLine("Couldn't convert value " + value + " to Int32");
return Int32.MaxValue;
}
else if (value < Int32.MinValue)
{
Console.WriteLine("Couldn't convert value " + value + " to Int32");
return Int32.MinValue;
}
else
{
return Convert.ToInt32(value);
}
}
答案 0 :(得分:14)
同时检查double.IsNaN(value)
。
与NaN
比较总是产生错误。
答案 1 :(得分:3)
以下是Microsoft Convert.cs
的来源:
public static int ToInt32(double value) {
if (value >= 0) {
if (value < 2147483647.5) {
int result = (int)value;
double dif = value - result;
if (dif > 0.5 || dif == 0.5 && (result & 1) != 0) result++;
return result;
}
}
else {
if (value >= -2147483648.5) {
int result = (int)value;
double dif = value - result;
if (dif < -0.5 || dif == -0.5 && (result & 1) != 0) result--;
return result;
}
}
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
我不知道你喂它的价值是什么,但答案现在应该是显而易见的。
答案 2 :(得分:0)
每次使用任何双值运行此函数时都会出现异常吗?
它对我来说很好。
编辑:我使用以下代码创建了一个程序:
using System;
using System.Collections.Generic;
using System.Text;
namespace test1
{
class Program
{
static void Main(string[] args)
{
Int32 myInt = ConvertValue(86389327923.678);
Console.WriteLine(myInt);
myInt = ConvertValue(-86389327923.678);
Console.WriteLine(myInt);
myInt = ConvertValue(8.678);
Console.WriteLine(myInt);
Console.ReadKey();
}
static private Int32 ConvertValue(double value)
{
if (value > Int32.MaxValue)
{
Console.WriteLine("Couldn't convert value " + value + " to Int32");
return Int32.MaxValue;
}
else if (value < Int32.MinValue)
{
Console.WriteLine("Couldn't convert value " + value + " to Int32");
return Int32.MinValue;
}
else
{
return Convert.ToInt32(value);
}
}
}
}