Re: [問題] 新手問題 (string)123
※ 引述《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)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 3 篇):
C_Sharp 近期熱門文章
PTT數位生活區 即時熱門文章