Convert.ToInt32和(INT)之间的区别 [英] difference between Convert.ToInt32 and (int)

查看:513
本文介绍了Convert.ToInt32和(INT)之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下语法抛出一个编译时错误,如

无法转换类型'字符串'到'廉政'

 字符串名称=(会话[名称1]的ToString());
INT I =(int)的名称;

而code编译如下,并成功执行

 字符串名称=(会话[名称1]的ToString());
INT I = Convert.ToInt32(名);

我想知道


  1. 为什么在发生编译时错误
    第一code


  2. 什么是2之差
    code片段



解决方案

(INT)富简直就是投给的Int32 (<在C#code> INT )类型。这是内置在CLR和要求是一个数字的变量(例如浮动等)。在这个意义上,这是非常类似于C铸

Convert.ToInt32 的设计是一般的转换功能。它做一个很好的协议比铸造以上;即,它可以从的任何的原始类型到 INT (最值得注意的是,解析字符串)。你可以看到重载这个方法这里MSDN 的完整列表。

the following syntax throws an compile time error like

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);

I would like to know

  1. why the compile time error occurs in first code

  2. what's the difference between the 2 code snippets

解决方案

(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 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.

这篇关于Convert.ToInt32和(INT)之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆