遇到了OverflowException

12 .net c#

在最后一行的下面的方法中,我总是得到一个例外:

System.OverflowException: Value was either too large or too small for an Int32.
Run Code Online (Sandbox Code Playgroud)

我无法解释为什么,因为我正在明确检查:

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);
   }
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*rik 14

还检查一下double.IsNaN(value).

比较NaN总是产生错误.