最近的 question came up关于使用 String.Format()。我的部分回答包括使用 StringBuilder.AppendLine(string.Format(...)) 的建议。 Jon Skeet 认为这是一个不好的例子,并建议使用 AppendLine 和 AppendFormat 的组合。
我突然想到,我从来没有真正让自己适应使用这些方法的“首选”方法。我想我可能会开始使用类似以下的东西,但我很想知道其他人使用什么作为“最佳实践”:
sbuilder.AppendFormat("{0} line", "First").AppendLine();
sbuilder.AppendFormat("{0} line", "Second").AppendLine();
// as opposed to:
sbuilder.AppendLine( String.Format( "{0} line", "First"));
sbuilder.AppendLine( String.Format( "{0} line", "Second"));
最佳答案
我认为 AppendFormat
后跟 AppendLine
不仅更具可读性,而且比调用 AppendLine(string.Format(...))
。
后者创建一个全新的字符串,然后将其全部附加到现有的构建器中。我不会说“那为什么还要使用 StringBuilder 呢?”但这似乎有点违背 StringBuilder 的精神。
关于c# - 您何时使用 StringBuilder.AppendLine/string.Format 与 StringBuilder.AppendFormat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/349724/