C#:最可读的字符串连接。最佳实践 [英] C#: most readable string concatenation. best practice
问题描述
可能重复:结果
的我应该如何连接字符串?
有几种方法在日常任务CONCAT字符串时表现的未重要。一>
There are several ways to concat strings in everyday tasks when performance is not important.
-
的结果= A +:+ b
-
结果= string.Concat(一个:,C)
-
结果=的String.Format({0}:{1},A,b);
-
StringBuilder的方法
- ...
result = a + ":" + b
result = string.Concat(a, ":", c)
result = string.Format("{0}:{1}", a, b);
StringBuilder approach
- ... ?
做什么你喜欢,为什么,如果效率并不重要,但你要保持最可读的为你的口味的代码?
what do you prefer and why if efficiency doesn't matter but you want to keep the code most readable for your taste?
推荐答案
的String.Format
对我来说,但在实践中我使用取其适合于目的,兼顾性能和可读性。
string.Format
for me, but in practice I use whichever is fit for purpose, taking into account performance and readability.
如果是两个变量,我会使用。
If it was two variables I'd use.
string.Concat(STR1,STR2);
如果它包含了一个常量或东西,需要的格式即可。
If it contained a constant or something that requires formatting then.
的String.Format({0} + {1} = {2},X,Y,X + Y);
或为类似SQL查询
string SqlQuery = "SELECT col1, col2, col3, col4" +
"FROM table t " +
"WHERE col1 = 1";
和字符串生成器时的性能问题。
And string builder when performance matters.
这篇关于C#:最可读的字符串连接。最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!