作者ssccg (23)
看板C_Sharp
标题Re: [问题] 新手问题 (string)123
时间Mon Jan 28 20:45:46 2013
※ 引述《putumaxally (Puma)》之铭言:
: 可以请问一下为什麽 不能用(string)123把int转成string
: 用Convert.ToString(123)跟123.ToString()就可以
: 数字型别的转换就不会有出错。
:
: 我还是不了解为什麽不能使用(string)123把数字转成字串
: 而Convert.ToString(123)跟123.ToString()
: 或是把数字加上字串的implicit conversion 都能转换
: (string)跟上面三种的差异在哪里??
因为C#
没有定义这个转换
数字可以互转是因为C#有定义数字间的转换
http://msdn.microsoft.com/en-us/library/y5b434w4.aspx
http://msdn.microsoft.com/en-us/library/yht2cx7b.aspx
Convert.ToString(123)可以用是因为Convert有定义这个方法
http://msdn.microsoft.com/en-us/library/x70d7t0y.aspx
123.ToString()可以用是因为Int32定义有override ToString这个方法
回传值的string是这个数字的表示法
http://msdn.microsoft.com/en-us/library/6t7dwaa5.aspx
数字加上字串的转换,是因为C#语言规格中operator +的定义包含以下
string operator +(string x, object y)
{ return x + (y != null ? y.ToString() : ""); }
string operator +(object x, string y)
{ return (x != null ? x.ToString() : "") + y; }
这其实不是转换,是呼叫ToString方法
http://msdn.microsoft.com/zh-tw/vcsharp/aa336809.aspx
一般的reference type可以用(class-type)转换是因为C#语言规格有定义
derived class可以implicit convert到base class
base class可以explicit convert到derived class
(还有其他转换定义可以参考C#语言规格第6章)
而string是个class-type,int是value-type
C#没有定义int到string这个转换
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 219.71.89.9
※ 编辑: ssccg 来自: 219.71.89.9 (01/28 20:55)