2013-07-25 24 views
1

爲什麼這個奇怪的事情發生了,當我嘗試通過的WriteLine的char [] +東西

Console.WriteLine(word); 

char[] word到一個控制檯我得到一個正確的結果,但是當我寫

Console.WriteLine(word + " something"); 

我得到「System.Char[]東西」?

回答

3

出現這種情況數組,其中Console.WriteLine接受使用過載的有效輸入。

Console.WriteLine(word); 

但是,因爲你正在結合用字符串字面char[]你的第二個結果出現錯誤。所以Console.WriteLine試圖讓你的char[]也是一個字符串,這樣做:

Console.WriteLine(word.ToString() + " something"); 

注意到它的word(內部)調用.ToString(),使之成爲stringchar[]上的ToString方法返回它的類型不是它的值。因此給你一個奇怪的結果。

您可以通過執行修復:

Console.WriteLine(new string(word) + " something"); 
1

這是因爲

Console.WriteLine(word); 

其調用WriteLine過載,這需要char[]

Console.WriteLine(word + " something"); 

了呼叫ToString()word其正確導致System.Char[]

爲了輸出它,嘗試:因爲你的第一次嘗試寫了char

Console.WriteLine(new string(word) + " something"); 
0

爲什麼會發生是重載運算符+會那樣的原因。 如果你想使用這種方式,你必須首先從你的char []字中創建一個字符串。 嘗試

Console.WriteLine(new string(word) + " something"); 
+0

確定'string(word)'是否有效?因爲它說「無效的表達式字符串」 – user2542809

+0

新字符串(字)應該 – mewa

0

Console.WriteLine()具有overload這需要char[]作爲參數。

"something"string literal,當您嘗試來連接stringchar[].ToString()方法調用自動。

試試這個,而不是;

Console.WriteLine(new string(word) + " something");