C# 使用“+”运算符的字符串连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10341188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:28:06  来源:igfitidea点击:

String Concatenation using '+' operator

c#.netstring

提问by NoviceProgrammer

Looking at the stringclass metadata, I only see the operators ==and !=overloaded. So how is it able to perform concatenation for the '+' operator?

查看string类元数据,我只看到运算符==!=重载。那么它如何能够为 ' +' 运算符执行连接?

Edit:

编辑

Some interesting notes from Eric Lippert on string concatenation:

Eric Lippert 关于字符串连接的一些有趣笔记:

Part 1

第1部分

Part 2

第2部分

There is also a super article from Joel referred in part 2 (http://www.joelonsoftware.com/articles/fog0000000319.html)

还有一篇来自 Joel 的超级文章在第 2 部分中提到(http://www.joelonsoftware.com/articles/fog0000000319.html

采纳答案by Jon Skeet

It doesn't - the C# compiler does :)

它没有 - C# 编译器有 :)

So this code:

所以这段代码:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

实际上被编译为:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

(Gah - 干预编辑意外删除了其他位。)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + ywhich then needs to be copied again as part of the concatenation of (x + y)and z. Instead, we get it all done in one go.

C# 编译器注意到这里有多个字符串连接的好处是,您最终不会创建一个中间字符串x + y,然后需要再次复制它作为(x + y)和连接的一部分z。相反,我们一次性完成所有工作。

EDIT: Note that the compiler can'tdo anything if you concatenate in a loop. For example, this code:

编辑:请注意,如果您在循环中连接,编译器将无法执行任何操作。例如,这段代码:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

最终等同于:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this doesgenerate a lot of garbage, and it's why you should use a StringBuilderfor such cases. I have an article going into more details about the twowhich will hopefully answer further questions.

...所以这确实会产生很多垃圾,这就是为什么你应该StringBuilder在这种情况下使用 a 。我有一篇文章详细介绍了这两者,希望能回答更多问题。