C# 你什么时候使用 StringBuilder.AppendLine/string.Format 和 StringBuilder.AppendFormat?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/349724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When do you use StringBuilder.AppendLine/string.Format vs. StringBuilder.AppendFormat?
提问by Neil Barnwell
A recent question came upabout using String.Format(). Part of my answer included a suggestion to use StringBuilder.AppendLine(string.Format(...)). Jon Skeet suggested this was a bad example and proposed using a combination of AppendLine and AppendFormat.
最近出现了一个关于使用 String.Format() 的问题。我的部分答案包括使用 StringBuilder.AppendLine(string.Format(...)) 的建议。Jon Skeet 认为这是一个糟糕的例子,并建议使用 AppendLine 和 AppendFormat 的组合。
It occurred to me I've never really settled myself into a "preferred" approach for using these methods. I think I might start using something like the following but am interested to know what other people use as a "best practice":
我突然想到,我从来没有真正让自己适应使用这些方法的“首选”方法。我想我可能会开始使用类似以下的东西,但我很想知道其他人使用什么作为“最佳实践”:
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"));
采纳答案by Jon Skeet
I view AppendFormat
followed by AppendLine
as not only more readable, but also more performant than calling AppendLine(string.Format(...))
.
我认为AppendFormat
followAppendLine
不仅更具可读性,而且比调用AppendLine(string.Format(...))
.
The latter creates a whole new string and then appends it wholesale into the existing builder. I'm not going to go as far as saying "Why bother using StringBuilder then?" but it does seem a bit against the spirit of StringBuilder.
后者创建一个全新的字符串,然后将其批量附加到现有的构建器中。我不会说“那为什么还要使用 StringBuilder 呢?” 但这似乎有点违背 StringBuilder 的精神。
回答by Brian Genisio
AppendFormat() is a lot more readable than AppendLine(String.Format())
AppendFormat() 比 AppendLine(String.Format()) 更具可读性
回答by Joel Coehoorn
I prefer this structure:
我更喜欢这种结构:
sbuilder.AppendFormat("{0} line\n", "First");
Though admittedly there is something to be said for separating out the line breaks.
虽然不可否认,对于分隔换行符有一些话要说。
回答by Coderer
Is it just positively awful to simply use
简单地使用它是不是真的很糟糕
sbuilder.AppendFormat("{0} line\n", first);
? I mean, I know it's not platform-independent or whatever, but in 9 out of 10 cases it gets the job done.
? 我的意思是,我知道它不是独立于平台的或其他什么,但是在十分之九的情况下它可以完成工作。
回答by Chris
If performance is important, try to avoid AppendFormat() completely. Use multiple Append() or AppendLine() calls instead. This does make your code larger and less readable, but it's faster because no string parsing has to be done. String parsing is slower than you might imagine.
如果性能很重要,请尽量避免使用 AppendFormat()。改用多个 Append() 或 AppendLine() 调用。这确实会使您的代码更大且可读性更低,但速度更快,因为不必进行字符串解析。字符串解析比您想象的要慢。
I generally use:
我一般使用:
sbuilder.AppendFormat("{0} line", "First");
sbuilder.AppendLine();
sbuilder.AppendFormat("{0} line", "Second");
sbuilder.AppendLine();
Unless performance is critical, in which case I'd use:
除非性能至关重要,在这种情况下我会使用:
sbuilder.Append("First");
sbuilder.AppendLine(" line");
sbuilder.Append("Second");
sbuilder.AppendLine(" line");
(Of course, this would make more sense if "First" and "Second" where not string literals)
(当然,如果“第一”和“第二”不是字符串文字,这会更有意义)
回答by AdamSane
String.format creates a StringBuilder object internally. By doing
String.format 在内部创建一个 StringBuilder 对象。通过做
sbuilder.AppendLine( String.Format( "{0} line", "First"));
an additional instance of string builder, with all of its overhead is created.
创建了一个额外的字符串构建器实例,并创建了它的所有开销。
Reflector on mscorlib, Commonlauageruntimelibary, System.String.Format
mscorlib、Commonlauageruntimelibary、System.String.Format 上的反射器
public static string Format(IFormatProvider provider, string format, params object[] args)
{
if ((format == null) || (args == null))
{
throw new ArgumentNullException((format == null) ? "format" : "args");
}
StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));
builder.AppendFormat(provider, format, args);
return builder.ToString();
}
回答by docmanhattan
Just create an extension method.
只需创建一个扩展方法。
public static StringBuilder AppendLine(this StringBuilder builder, string format, params object[] args)
{
builder.AppendFormat(format, args).AppendLine();
return builder;
}
Reasons I prefer this:
我喜欢这个的原因:
- Doesn't suffer as much overhead as
AppendLine(string.Format(...))
, as stated above. - Prevents me from forgetting to add the
.AppendLine()
part at the end (happens frequently enough). - Is more readable (but that is more of an opinion).
- 不会
AppendLine(string.Format(...))
像上面所说的那样承受那么多的开销。 - 防止我忘记
.AppendLine()
在最后添加部分(经常发生)。 - 更具可读性(但这更多是一种意见)。
If you don't like it being called 'AppendLine,' you could change it to 'AppendFormattedLine' or whatever you want. I enjoy everything lining up with other calls to 'AppendLine' though:
如果您不喜欢它被称为“AppendLine”,您可以将其更改为“AppendFormattedLine”或任何您想要的。不过,我喜欢与其他对“AppendLine”的调用对齐的所有内容:
var builder = new StringBuilder();
builder
.AppendLine("This is a test.")
.AppendLine("This is a {0}.", "test");
Just add one of these for each overload you use of the AppendFormat method on StringBuilder.
只需为您在 StringBuilder 上使用 AppendFormat 方法的每个重载添加其中一个。