字符串连接+字符串连接的运算符在哪里?

Tim*_*ter 5 .net c# string operator-overloading

我最近想知道-operator的string重载位置+.我能看到的唯一方法是==!=.为什么两个字符串可以与+连接,即使该运算符没有重载?这只是一个神奇的编译器技巧还是我错过了什么?如果是前者,为什么以这种方式设计字符串?

这个问题就是从这里提出的.很难解释某人他不能+用来连接两个对象,因为object如果string不关心运算符也不会重载这个运算符.

Sri*_*vel 8

String不会使+运算符重载.它是c#编译器,它将对+operator 的调用转换为String.Concat方法.

请考虑以下代码:

void Main()
{
    string s1 = "";
    string s2 = "";

    bool b1 = s1 == s2;
    string s3 = s1 + s2;
}
Run Code Online (Sandbox Code Playgroud)

产生IL

IL_0001:  ldstr       ""
IL_0006:  stloc.0     // s1
IL_0007:  ldstr       ""
IL_000C:  stloc.1     // s2
IL_000D:  ldloc.0     // s1
IL_000E:  ldloc.1     // s2
IL_000F:  call        System.String.op_Equality //Call to operator
IL_0014:  stloc.2     // b1
IL_0015:  ldloc.0     // s1
IL_0016:  ldloc.1     // s2
IL_0017:  call        System.String.Concat // No operator call, Directly calls Concat
IL_001C:  stloc.3     // s3
Run Code Online (Sandbox Code Playgroud)

Spec在这里调用它7.7.4添加运算符,虽然它没有谈到调用String.Concat.我们可以假设它是实现细节.