我应该如何连接字符串?字符串

2023-09-02 10:38:07 作者:言不由衷

是否有这些例子之间的差异?其中我应该在这种情况下使用?

Are there differences between these examples? Which should I use in which case?

var str1 = "abc" + dynamicString + dynamicString2;

var str2 = String.Format("abc{0}{1}", dynamicString, dynamicString2);

var str3 = new StringBuilder("abc").
    Append(dynamicString).
    Append(dynamicString2).
    ToString();

var str4 = String.Concat("abc", dynamicString, dynamicString2);

有类似的问题:

Difference在字符串连接只询问了 + 操作符,它甚至没有在答题它转换为String.Concat提到 What's最好的字符串连接方法这是不是真的与我的问题,它是要求最好的,而不是来连接字符串和它们的输出,因为这个问题确实可能的方式一比较。 Difference in String concatenation which only asks about the + operator, and it's not even mentioned in the answer that it is converted to String.Concat What's the best string concatenation method which is not really related to my question, where it is asking for the best, and not a comparation of the possible ways to concatenate a string and their outputs, as this question does.

这个问题是问在每一种情况下会发生什么,会是怎样的这些例子的实际产出?什么是对他们的区别在哪里?我应该在哪里使用他们在这种情况下?

This question is asking about what happens in each case, what will be the real output of those examples? What are the differences about them? Where should I use them in which case?

推荐答案

收集来自所有的答案信息,它原来是这样的表现:

Gathering information from all the answers it turns out to behave like this:

+ 运营商是一样的 String.Concat ,这可能是外界的一个小串联使用环,可以用在小任务

The + operator is the same as the String.Concat, this could be used on small concatenations outside a loop, can be used on small tasks.

在编译的时候, + 运营商生成一个字符串,如果他们是静态的,而 String.Concat 产生前pression 海峡= STR1 + STR2; 即使是静态

In compilation time, the + operator generate a single string if they are static, while the String.Concat generates the expression str = str1 + str2; even if they are static.

的String.Format 是一样的的StringBuilder .. (例如3)除了的String.Format 确实PARAMS的验证和实例的内部的StringBuilder 的参数的长度。

String.Format is the same as StringBuilder.. (example 3) except that the String.Format does a validation of params and instantiate the internal StringBuilder with the length of the parameters.

的String.Format 时,应使用需要的格式字符串,并Concat的简单的字符串。

String.Format should be used when format string is needed, and to concat simple strings.

的StringBuilder 当你需要连接大字符串或在循环中应使用。

StringBuilder should be used when you need to concatenate big strings or in a loop.