【问题标题】:String.Format vs + C# [duplicate]String.Format vs + C# [重复]
【发布时间】:2014-04-27 08:27:34
【问题描述】:

可能重复:
When is it better to use String.Format vs string concatenation?

在 C# 中使用 String.Format 时的最佳实践是什么。我总是在这里感到困惑,因为这样做似乎更简单

    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 与仅使用字符串连接相比有什么特别的优势吗?换句话说,我可以这样做......,

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

我想继续追求质量代码,但我不知道它的quality 何时使用String.Format。如果有人有任何建议,我将不胜感激。

【问题讨论】:

标签: c# string


【解决方案1】:

在这种情况下,我会使用直接连接; MS 认证文章建议仅对两个字符串进行简单连接。

如果您的变量是 DateTime 对象(例如)并且您需要特定格式,那么我会使用 String.Format。

【讨论】:

    【解决方案2】:

    当您需要将应用程序翻译成多种语言或应对不同的环境时,String.Format 将为您提供帮助。如果你从一开始就使用它 string.format,你会让自己处于一个更好的位置,因为将所有字符串放入资源文件会更容易。

    在您的示例中,如果您使用 string.format,然后选择将 Start Info 字符串存储在资源文件中,您可以为不同的环境提供单独的资源文件以支持 MAC、windows 和 Linux,而无需更改代码。

    【讨论】:

      【解决方案3】:

      String.Format 更具可读性,而字符串连接速度更快。 String.Format 使用内部的 StringBuilder 来格式化字符串,所以它有点慢但更健壮。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-07
        相关资源
        最近更新 更多