刚开始使用C#,在查看教程时,我发现连接(用户是字符串变量的console.writeline("Hello" + user)
)和占位符({{1}之间没有任何区别其中user是字符串变量)输出方法。是否存在差异,或者只是简单地找到哪种方式
答案 0 :(得分:2)
它并不是特定于C#,许多语言都支持这两种风格。后一种形式通常被认为是“更安全”,但我无法引用任何具体原因。如果项目需要出现在多个位置,或者您希望将格式字符串保存为常量,则非常有用。请查看此主题以获取更多信息:When is it better to use String.Format vs string concatenation?。
答案 1 :(得分:1)
使用字符串格式化程序,而不是字符串连接,几乎完全是关于可读性。他们实际上做什么,甚至他们的表现如何,都足够接近。
对于这样一个简单的情况,两者看起来都很好,但是当你有一个复杂的字符串,其中有很多值混合在格式字符串中时,最终会看起来更好:
这是一个更好的例子:
string output = "Hello " + username + ". I have spent " + executionTime + " seconds trying to figure out that the answer to life is: " + output;
vs
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);
答案 2 :(得分:0)
正如Matt所说,Place holding被认为是更安全的方法,然后是简单的连接,但我不确定是否有这个原因(我需要对它进行探索)。但有一件事是肯定的是,Place Holding在性能方面的连接是有点昂贵的。请查看Jon Skeet的Blog entry "Formatting Strings"。
虽然只有在使用Place Holders几千次左右时,性能才会有显着影响。