问题描述
以下代码会引发类似的编译时错误
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);
我想知道:
为什么第一个代码会产生编译时错误?
Why does the the first code generate a compile-time error?
这两个代码片段有什么区别?
What's the difference between the 2 code snippets?
推荐答案
(int)foo
只是对 Int32
(int
在 C# 中) 类型.这是内置在 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
truncatesfoo
(ifoo = Math.Floor(foo)
), whileConvert.ToInt32(foo)
uses half to even rounding (rounds x.5 to the nearest EVEN integer, meaningifoo = Math.Round(foo)
). The result is thus not just implementation-wise, but also numerically not the same.
这篇关于Convert.ToInt32 和 (int) 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!