我想知道在c#.net中的类型转换,我有下面的代码行。类型铸造在c#.net
int i=4
object o = i // This works properly without any typecasting becausing boxing takes place automatically
string s= i // This does not work, even when the string is also reference type?
string s=(string)i //This also does not work even if i try to typecast the int to string.
string s= Convert.ToString(i); // this works.
,所以我想知道为什么string s = i and string s = (string)i
不使用(string)i, i.ToString(), and Convert.ToString(i)
工作和最新的差异。
“类型CASTING是类型的CAST,而不是转换。它只适用于包含字符串或字符串子类的情况。” - 它可以是转换,如果定义了一个? – Rawling 2012-02-27 10:06:22
如果定义了隐式转换,它可以是一个。不知道这也适用于拆箱 - 但它必须通过运营商超载作为转换。 – TomTom 2012-02-27 10:07:36
所以它的意思是,string(i)和i.ToString()是相同的,它会尝试转换类型,对吧? – Abbas 2012-02-27 10:11:03