MSDN說我們需要將StringBuilder
對象轉換爲string
,但StringBuilder
工作正常嗎? 我們爲什麼要轉換?爲什麼我們應該使用StringBuilder的ToString方法?
string[] spellings = { "hi", "hiii", "hiae" };
StringBuilder Builder = new StringBuilder();
int counter = 1;
foreach (string value in spellings)
{
Builder.AppendFormat("({0}) Which is Right spelling? {1}", counter, value);
Builder.AppendLine();
counter++;
}
Console.WriteLine(Builder); // Works Perfectly
//Why should i use tostring like below
Console.WriteLine(Builder.ToString());
// Does it make any difference in above two ways.
Console.ReadLine();
沒有爲StringBuilder的沒有個Console.WriteLine覆蓋所以它只是調用Object arg然後在內部使用.ToString(),所以它們都做同樣的事情 – acrilige
如果明確調用Console.WriteLine,則不需要使用'.ToString()',但是你幾乎所有其他的東西都需要它 – Jon