Convert.ToInt32和(int)有什么区别?

问题描述:

以下代码会引发编译时错误,例如

The following code throws an compile-time error like

无法将类型'string'转换为'int'

Cannot convert type 'string' to 'int'

string name = Session["name1"].ToString();
int i = (int)name;

而下面的代码可以编译并成功执行:

whereas the code below compiles and executes successfully:

string name = Session["name1"].ToString();
int i = Convert.ToInt32(name);

我想知道:


  1. 为什么第一个代码会生成编译时错误?

  1. Why does the the first code generate a compile-time error?

这两个代码段之间有什么区别?

What's the difference between the 2 code snippets?


(int)foo 只是对 Int32 (在C#中为 int )类型的转换。这是CLR内置的,要求 foo 是数字变量(例如 float long 等)。在这种意义上,它与C中的强制转换非常相似。

(int)foo is simply a cast to the Int32 (int in C#) type. This is built into the CLR and requires that foo be a numeric variable (e.g. float, long, etc.) In this sense, it is very similar to a cast in C.

Convert.ToInt32 被设计为通用转换函数。它比铸造更重要。也就是说,它可以从 any 基本类型转换为 int (最值得注意的是,解析 string )。您可以在MSDN上的此处查看重载的完整列表

Convert.ToInt32 is designed to be a general conversion function. It does a good deal more than casting; namely, it can convert from any primitive type to a int (most notably, parsing a string). You can see the full list of overloads for this method here on MSDN.

Stefan Steiger 提到在评论中


此外,请注意,在数字级别上,(int)foo 会截断 foo ifoo = Math.Floor(foo)),而 Convert.ToInt32(foo)使用一半舍入为四舍五入(将x.5舍入为最接近的EVEN整数,表示 ifoo = Math.Round(foo))。因此,结果不仅是实现方面的,而且在数字上也是如此。

Also, note that on a numerical level, (int) foo truncates foo (ifoo = Math.Floor(foo)), while Convert.ToInt32(foo) uses half to even rounding (rounds x.5 to the nearest EVEN integer, meaning ifoo = Math.Round(foo)). The result is thus not just implementation-wise, but also numerically not the same.