2012-03-19 73 views
1

可能重複:
When is it better to use String.Format vs string concatenation?的String.Format VS + C#

使用的String.Format爲C#時,什麼是最好的做法。我總是感到困惑,在這裏,因爲它只是似乎更簡單的方式做業務這樣

private string _ExecuteCommand(string cmd) 
    { 
     // Start the child process. 
     Process p = new Process(); 
     ProcessStartInfo startInfo = new ProcessStartInfo(); 

     // Redirect the output stream of the child process. 
     startInfo.WindowStyle = ProcessWindowStyle.Hidden; 
     startInfo.FileName = "cmd.exe"; 
     startInfo.Arguments = String.Format("/C {0}", cmd); // prevents the command line from staying open after execution 

     //... you get the idea 
    } 

是否有特定的優勢使用的String.Format VS只是字符串連接?換句話說,我可以做到這一點,而不是...,

startInfo.Arguments = "/C " + cmd; // prevents the command line from staying open after execution 

我想繼續persue高質量的代碼,但我不知道什麼時候它quality使用的String.Format。如果有人有任何建議,我將不勝感激。

+1

嗨,這將有助於:http://stackoverflow.com/questions/296978/when-is-it-better-to-use-string-format-vs-string-concatenation歡呼! – 2012-03-19 22:39:05

+0

哎呀對不起!我在SO上尋找這個,我必須錯過它。 – Michael 2012-03-19 22:39:26

回答

0

當您需要將您的應用翻譯成多種語言或應對不同的環境時,String.Format將爲您提供幫助。如果您從一開始就使用string.format,那麼您將自己置於一個更好的地方,因爲將所有字符串放入資源文件會更容易。

在您的示例中,如果您使用string.format,然後選擇將開始信息字符串存儲在資源文件中,則可以爲不同環境提供單獨的資源文件,以支持MAC,Windows和Linux,而無需更改代碼。

1

在這種情況下,我會直接連接; MS認證文章建議僅用於兩個字符串的簡單串接。

如果你的變量是一個DateTime對象(例如),你需要一個特定的格式,那麼我會使用String.Format。

0

字符串連接速度更快時,String.Format更具可讀性。 String.Format使用內部的StringBuilder來格式化字符串,所以它有點慢但更健壯。