简体   繁体   English

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

[英]Where does string overload + operator for string concatenation?

I recently wondered where string overloads the + -operator. 我最近想知道string重载+运算符的位置。 The only methods i can see are == and != . 我能看到的唯一方法是==!= Why can two strings be concatenated with + even if that operator is not overloaded? 为什么两个字符串可以与+连接,即使该运算符没有重载? Is this just a magic compiler trick or am i missing something? 这只是一个神奇的编译器技巧还是我错过了什么? If the former, why was string designed in that way? 如果是前者,为什么以这种方式设计字符串?

This question was raised from this . 这个问题就是从这里提出的。 It's difficult to explain someone that he cannot use + to concatenate two objects since object does not overload this operator if string does not care about overloading operators either. 很难解释某人他不能使用+来连接两个对象,因为如果string不关心运算符的重载,则object不会重载此运算符。

String doesn't overload + operator. String不会重载+运算符。 It is the c# compiler which converts the call to + operator to String.Concat method. 它是c#编译器,它将对+运算符的调用转换为String.Concat方法。

Consider the following code: 请考虑以下代码:

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

    bool b1 = s1 == s2;
    string s3 = s1 + s2;
}

Produces the IL 产生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

Spec calls this out here 7.7.4 Addition operator , though it doesn't talks about call to String.Concat . Spec在这里调用它7.7.4添加运算符 ,虽然它没有讨论对String.Concat调用。 We can assume it is implementation detail. 我们可以假设它是实现细节。

This quote is from C# 5.0 Specification 7.8.4 Addition operator 该引用来自C# 5.0 Specification 7.8.4 Addition operator

String concatenation: 字符串连接:

string operator +(string x, string y); 
string operator +(string x, object y); 
string operator +(object x, string y); 

These overloads of the binary + operator perform string concatenation. 二进制+运算符的这些重载执行字符串连接。 If an operand of string concatenation is null, an empty string is substituted. 如果字符串连接的操作数为null,则替换空字符串。 Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString method inherited from type object. 否则,通过调用从类型对象继承的虚拟ToString方法,将任何非字符串参数转换为其字符串表示形式。 If ToString returns null, an empty string is substituted. 如果ToString返回null,则替换空字符串。

I'm not sure why is mentions about overloading though.. Since we don't see any operator overloads. 我不确定为什么会提到过载 ...因为我们没有看到任何运算符重载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM