C#+运算符调用string.concat函数?

Var*_*rma 5 c# string operator-overloading concatenation

可能重复:
C#是否优化了字符串文字的串联?

我刚刚发现我们写了这样的一行:

string s = "string";
s = s + s; // this translates to s = string.concat("string", "string");
Run Code Online (Sandbox Code Playgroud)

但是我通过反射器打开了字符串类,我没看到这个+运算符在哪里重载?我可以看到==和!=超载.

[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);
    }
Run Code Online (Sandbox Code Playgroud)

那么为什么当我们使用+来组合字符串时会调用concat?

谢谢.

pho*_*oog 6

那么为什么当我们使用+来组合字符串时会调用concat?

C#规范的第7.7.4节"加法运算符"定义了字符串的二进制加法运算符,其中运算符返回操作数的串联.

System.StringCLI规范中的定义包括几个Concat重载,但没有+运算符.(我没有一个明确的答案解释这个遗漏,但我想这是因为有些语言定义了除+字符串连接之外的运算符.)

鉴于这两个事实,C#编译器编写器最合乎逻辑的解决方案是String.Concat在编译+(string, string)运算符时发出调用.

  • +1:对于所有信息...希望有人会提供有关该问题的更多信息 (2认同)

Gui*_*ume 5

代码

    public string Foo(string str1, string str2)
    {
        return str1 + str2;
    }
Run Code Online (Sandbox Code Playgroud)

给出以下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
Run Code Online (Sandbox Code Playgroud)

编译器(至少是Visual Studio 2010中的编译器)完成此任务,并且没有+重载.