查看 string
类元数据,我只看到运算符 ==
和 !=
重载了。那么它是如何为 '+
' 运算符执行连接的呢?
编辑:
Eric Lippert 关于字符串连接的一些有趣笔记:
第 2 部分中还引用了 Joel 的一篇 super 文章 ( http://www.joelonsoftware.com/articles/fog0000000319.html )
最佳答案
它不会 - C# 编译器会:)
所以这段代码:
string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;
实际上编译为:
string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);
(Gah - 干预编辑不小心删除了其他位。)
C# 编译器注意到这里有多个字符串连接的好处是您不会最终创建 x + y
的中间字符串,然后需要将其作为(x + y)
和 z
的串联。相反,我们一次性完成所有工作。
编辑:请注意,如果您在循环中连接,编译器不能做任何事情。例如,这段代码:
string x = "";
foreach (string y in strings)
{
x += y;
}
只是最终等同于:
string x = "";
foreach (string y in strings)
{
x = string.Concat(x, y);
}
... 所以这确实 产生了很多垃圾,这就是为什么您应该在这种情况下使用StringBuilder
。我有一个 article going into more details about the two这有望回答更多问题。
关于c# - 使用 '+' 运算符的字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10341188/