2008-12-08 67 views
50

最近關於使用String.Format()的question came up。我的部分答案包括使用StringBuilder.AppendLine(string.Format(...))的建議。喬恩Skeet建議這是一個不好的例子,並建議使用AppendLine和AppendFormat的組合。什麼時候使用StringBuilder.AppendLine/string.Format與StringBuilder.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")); 
+0

也許你的代碼示例可以說明兩種情況? :) – annakata 2008-12-08 14:44:05

回答

56

我認爲AppendFormat其次AppendLine因爲不僅更具有可讀性,也比更好的性能請撥打AppendLine(string.Format(...))

後者創建一個全新的字符串,然後將其批量添加到現有的構建器中。我不打算說「爲什麼麻煩使用StringBuilder呢?」但它確實有點違背了StringBuilder的精神。

+0

是的,我會完全採取這一點(並感謝首先帶我,順便說一句)。 – 2008-12-08 14:39:17

+1

沒問題 - 對不起,如果我的語氣在原評論中顯得粗糙。多任務處理有時候對我有用:( – 2008-12-08 14:40:31

0

AppendFormat()是一個很多比AppendLine更具可讀性(的String.Format())

0

我更喜歡這樣的結構:

sbuilder.AppendFormat("{0} line\n", "First"); 

但無可否認也有一些是用於分離出的線可說的休息。

+1

我想「jinx」不適用於SO,是不是? – Coderer 2008-12-08 14:53:38

0

難道只是積極可怕簡單地使用

sbuilder.AppendFormat("{0} line\n", first); 

?我的意思是,我知道它不是獨立於平臺的或不管什麼,但在10個案例中有9個完成了工作。

2

如果性能很重要,請儘量避免使用AppendFormat()。改用多個Append()或AppendLine()調用。這確實會讓你的代碼變得更大,可讀性更差,但速度更快,因爲不需要進行字符串分析。字符串解析比你想像的要慢。

我一般用:

sbuilder.AppendFormat("{0} line", "First"); 
sbuilder.AppendLine(); 
sbuilder.AppendFormat("{0} line", "Second"); 
sbuilder.AppendLine(); 

除非性能是至關重要的,在這種情況下,我會使用:

sbuilder.Append("First"); 
sbuilder.AppendLine(" line"); 
sbuilder.Append("Second"); 
sbuilder.AppendLine(" line"); 

(當然,這會更有意義,如果「第一」和「第二個「沒有字符串文字的地方)

11

String.format在內部創建一個StringBuilder對象。通過做

sbuilder.AppendLine(String.Format("{0} line", "First")); 

字符串生成器的一個額外的實例,其所有的開銷創建。


反射器上的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(); 
} 
11

只需創建一個擴展方法。

public static StringBuilder AppendLine(this StringBuilder builder, string format, params object[] args) 
{ 
    builder.AppendFormat(format, args).AppendLine(); 
    return builder; 
} 

原因,我更喜歡這樣的:

  • 不遭受太大開銷AppendLine(string.Format(...)),如上所述。
  • 防止我忘記在末尾添加.AppendLine()部件(經常發生)。
  • 更具可讀性(但更多的是意見)。

如果您不喜歡它被稱爲'AppendLine',您可以將其更改爲'AppendFormattedLine'或任何你想要的。我喜歡一切都排着隊與其他呼叫「AppendLine」雖然:

var builder = new StringBuilder(); 

builder 
    .AppendLine("This is a test.") 
    .AppendLine("This is a {0}.", "test"); 

只需添加下列內容之一,每次使用StringBuilder的上的AppendFormat方法的重載。

相關問題