Convert.ToInt32和(INT)之间的区别 [英] difference between Convert.ToInt32 and (int)
问题描述
以下语法抛出一个编译时错误,如
无法转换类型'字符串'到'廉政'
字符串名称=(会话[名称1]的ToString());
INT I =(int)的名称;
而code编译如下,并成功执行
字符串名称=(会话[名称1]的ToString());
INT I = Convert.ToInt32(名);
我想知道
-
为什么在发生编译时错误
第一code -
什么是2之差
code片段
(INT)富
简直就是投给的Int32
(<在C#code> INT )类型。这是内置在CLR和要求富
是一个数字的变量(例如浮动
,长
等)。在这个意义上,这是非常类似于C铸
Convert.ToInt32
的设计是一般的转换功能。它做一个很好的协议比铸造以上;即,它可以从的任何的原始类型到 INT
(最值得注意的是,解析字符串$ C $转换C>)。你可以看到重载这个方法这里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
why the compile time error occurs in first code
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屋!