Reg*_*ser 4 c# string stringbuilder tostring
MSDN说我们需要将StringBuilder
对象转换为string
,但StringBuilder
工作正常吗?我们为什么要转换?
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();
Run Code Online (Sandbox Code Playgroud)
Mar*_*zek 10
这两个调用使用不同的Console.WriteLine
重载:WriteLine(Object)
和WriteLine(String)
.
并且WriteLine(object)
重载调用"...调用值的ToString方法以生成其字符串表示,并将结果字符串写入标准输出流." (msdn)
编辑
我能看到的唯一区别是:
StringBuilder sb = null;
Console.WriteLine(sb); // prints terminator
Console.WriteLine(sb.ToString()); // throws NullReferenceException
Run Code Online (Sandbox Code Playgroud)