纵观字符串
类的元数据,我只看到了运营商 ==
和 !=
超载。那么它是如何能够执行串联的' +
操作符?
Looking at the string
class metadata, I only see the operators ==
and !=
overloaded. So how is it able to perform concatenation for the '+
' operator?
修改
从埃里克利珀对字符串连接一些有趣的注释:
Some interesting notes from Eric Lippert on string concatenation:
第1部分
第2部分
还有乔尔超级文章中提到的第2部分(http://www.joelonsoftware.com/articles/fog0000000319.html)
There is also a super article from Joel referred in part 2 (http://www.joelonsoftware.com/articles/fog0000000319.html)
这不 - 的C#编译器:)
It doesn't - the C# compiler does :)
所以这个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.)
C#编译器察觉到有多个字符串连接在这里的好处是,你最终不会创造中间串X + Y
然后还需要为的连接(X + Y)的一部分,再次复制
和以Z
。相反,我们得到这一切在一气呵成完成的。
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.
编辑:请注意,编译器的不能的做任何事情,如果你在一个循环串联。例如,该code:
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);
}
...所以这个的确实的产生大量的垃圾,这就是为什么你应该使用的StringBuilder
对于这样的情况。我有一个文章进入有关这两个希望这将回答进一步的问题的更多细节。
... 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.