使用’+’运算符的字符串连接

查看 string类元数据,我只看到操作符 ==!=被重载。那么,它如何能够执行’+’操作符串联?

编辑 :

Eric Lippert 关于字符串连接的一些有趣的注释:

第一部分

第二部分

还有第2部分(http://www.joelonsoftware.com/articles/fog0000000319.html)中提到的 Joel 的一篇 super 文章

149963 次浏览

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

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.)

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 + y which 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.

EDIT: Note that the compiler can't do 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 does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.