Convert.ToInt32
在传递 string
与 float/double
literal
var result = Convert.ToInt32(12.4);//returns 12
result = Convert.ToInt32(12.44);//returns 12
result = Convert.ToInt32(12.4444444);//returns 12
result = Convert.ToInt32("12.4"); // Input string was not in a correct format.
我了解 Convert.ToInt32
的不同重载正在为 string 调用和 float/double
问题是为什么这种不一致的行为不应该 single
为 Convert.ToInt32
重载而抛出精度丢失的异常?
最佳答案
The question is why this inconsistent behavior shouldn't single overload for Convert.ToInt32 throw an exception for loss of precision ?
您可以将当前用于将 double
转换为 int
的实用方法视为 “转换” 即 (int)12.4
, (int)12.44
等,这在本质上意味着你肯定知道你很可能会失去数据精度,因此简而言之就像告诉编译器 “继续转换它,因为我不介意数据丢失”,因此,不会抛出异常,而最后一个例子是从 string
转换为 int
应该 抛出异常,因为根据 MSDN:
ToInt32(String) method is equivalent to passing value to the Int32.Parse(String).
众所周知,如果指定的字符串格式不正确,Int32.Parse(String)
会抛出异常。
关于c# - Convert.ToInt32 行为字符串与 float / double 文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46140482/