Nei*_*ell 57 .net c# formatting stringbuilder
最近出现了一个关于使用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"));
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 61
我认为AppendFormat其后AppendLine不仅更具可读性,而且比调用更具性能AppendLine(string.Format(...)).
后者创建一个全新的字符串,然后将其批量附加到现有构建器中.我不打算说"为什么还要使用StringBuilder呢?" 但它似乎有点违背StringBuilder的精神.
doc*_*tan 13
只需创建一个扩展方法.
public static StringBuilder AppendLine(this StringBuilder builder, string format, params object[] args)
{
builder.AppendFormat(format, args).AppendLine();
return builder;
}
Run Code Online (Sandbox Code Playgroud)
我更喜欢这个的原因:
AppendLine(string.Format(...))如上所述,不会遭受如此多的开销..AppendLine()在最后添加部分(经常发生).如果您不喜欢它被称为'AppendLine',您可以将其更改为'AppendFormattedLine'或任何您想要的.我喜欢与"AppendLine"的其他调用排队的所有内容:
var builder = new StringBuilder();
builder
.AppendLine("This is a test.")
.AppendLine("This is a {0}.", "test");
Run Code Online (Sandbox Code Playgroud)
只需在StringBuilder上为AppendFormat方法使用的每个重载添加其中一个.
Ada*_*ane 11
String.format在内部创建一个StringBuilder对象.通过做
sbuilder.AppendLine( String.Format( "{0} line", "First"));
Run Code Online (Sandbox Code Playgroud)
字符串构建器的另一个实例,其所有开销都已创建.
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27141 次 |
| 最近记录: |