在下面最后一行的方法中,我总是得到一个异常:
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);
}
}发布于 2011-03-04 22:18:17
还要检查double.IsNaN(value)。
与NaN进行比较总是会产生false。
发布于 2011-03-04 22:18:23
这是来自微软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"));
}我不知道你给它增加了什么价值,但答案现在应该很明显了。
发布于 2011-03-04 22:17:59
您每次运行此函数时都会得到异常,是否具有任何双精度值?
它对我来说工作得很好。
编辑:我用下面的代码创建了一个程序:
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);
}
}
}
}https://stackoverflow.com/questions/5194854
复制相似问题