What is the difference between Convert.ToInt32 and (int)?(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);
我想知道:
为什么第一个代码会产生编译时错误?
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) footruncatesfoo(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) 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Convert.ToInt32 和 (int) 有什么区别?
基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
