C#+运算符调用string.concat函数?
可能重复:
C#是否优化了字符串文字的串联?
我刚刚发现我们写了这样一行:
string s = "string"; s = s + s; // this translates to s = string.concat("string", "string");
但是我通过reflection器打开了字符串类,我没看到这个+运算符在哪里重载? 我可以看到==和!=超载。
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] public static bool operator ==(string a, string b) { return string.Equals(a, b); } [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] public static bool operator !=(string a, string b) { return !string.Equals(a, b); }
那么为什么当我们使用+来组合字符串时会调用concat?
谢谢。
那么为什么当我们使用+来组合字符串时会调用concat?
C#规范的第7.7.4节“加法运算符”定义了字符串的二进制加法运算符,其中运算符返回操作数的串联。
CLI规范中System.String
的定义包括几个Concat
重载,但没有+
运算符。 (我没有一个明确的答案解释这个遗漏,但我想这是因为有些语言定义了+
以外的运算符来进行字符串连接。)
鉴于这两个事实,C#编译器编写器最合乎逻辑的解决方案是在编译+(string, string)
运算符时发出对String.Concat
的调用。
代码
public string Foo(string str1, string str2) { return str1 + str2; }
给出以下IL:
IL_0000: nop IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call string [mscorlib]System.String::Concat(string, string) IL_0008: stloc.0 IL_0009: br.s IL_000b IL_000b: ldloc.0 IL_000c: ret
编译器(至少是Visual Studio 2010中的编译器)完成此任务,并且没有+
重载。