【问题标题】:Is there a difference between concatenation and place holding in C# output or is it a matter of preference?C# 输出中的连接和占位之间有区别还是偏好问题?
【发布时间】:2013-01-23 09:52:42
【问题描述】:

刚开始第一次使用 C#,在浏览教程时,我没有发现串联(console.writeline("Hello" + user),其中用户是字符串变量)和占位符(console.writeline("Hello {0}" , user)之间的区别,其中user 是一个字符串变量)输出方法。是否有区别,或者只是您觉得哪种方式更容易

【问题讨论】:

  • {0} 用于格式化,您也可以查看Operator Overloading 例如string strHold += strHold + some string
  • 考虑使用 String.Format() 作为后一种使用方式。
  • 在我看来,格式化字符串更容易阅读和修改。我讨厌查看具有比实际字符更多的引号和加号的串联字符串。

标签: c# concatenation string-concatenation console.writeline


【解决方案1】:

它并不是真正特定于 C#,许多语言都支持这两种样式。后一种形式通常被认为“更安全”,但我无法引用任何具体原因。如果项目需要出现在 1 个以上的位置,或者要将格式字符串保存为常量,这很有用。请查看此线程以获取更多信息:When is it better to use String.Format vs string concatenation?

【讨论】:

    【解决方案2】:

    使用字符串格式化程序,而不是字符串连接,几乎完全是为了可读性。他们实际上做什么,甚至他们的表现,都非常接近。

    对于这样一个简单的情况,两者看起来都不错,但是当您有一个复杂的字符串,其中包含许多混合在格式字符串中的值时,最终看起来会更好:

    这是一个更好的例子:

    string output = "Hello " + username + ".  I have spent " + executionTime + " seconds trying to figure out that the answer to life is: " + output;
    

    对比

    string output = string.Format("Hello {0}.  I have spent {1} seconds trying to figure out that the answer to life is: {2}"
        , username, executionTime, output);
    

    【讨论】:

      【解决方案3】:

      正如马特所说,占位被认为是比简单串联更安全的方法,但出于这个原因我不确定(我需要对此进行探索)。但是,有一点可以肯定,就性能而言,Place Holding 的操作成本比 Concatenation 高。查看 Jon Skeet 的 Blog entry "Formatting Strings"

      虽然只有在您使用占位符大约数千次时才会显着影响性能。

      【讨论】:

        猜你喜欢
        • 2014-06-07
        • 2023-03-08
        • 2010-09-30
        • 2019-07-18
        • 2011-03-13
        • 2020-10-07
        • 1970-01-01
        • 1970-01-01
        • 2021-12-28
        相关资源
        最近更新 更多