代码之家  ›  专栏  ›  技术社区  ›  Tim Schmelter

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

  •  5
  • Tim Schmelter  · 技术社区  · 10 年前

    我最近想知道在哪里 string 重载 + -操作员。我能看到的唯一方法是 == and != 。为什么即使运算符没有重载,两个字符串也可以用+连接?这只是一个 魔术 编译器技巧还是我遗漏了什么?如果是前者,为什么字符串是这样设计的?

    这个问题是从 this 很难解释他无法使用的人 + 连接两个对象,因为 object 如果 一串 也不关心重载运算符。

    2 回复  |  直到 7 年前
        1
  •  9
  •   Sriram Sakthivel    10 年前

    字符串不重载 + 操作人员是c#编译器将调用转换为 + 操作员到 String.Concat 方法

    考虑以下代码:

    void Main()
    {
        string s1 = "";
        string s2 = "";
    
        bool b1 = s1 == s2;
        string s3 = s1 + s2;
    }
    

    生成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在这里调用这个 7.7.4 Addition operator ,虽然它没有提到呼叫 字符串.凹形 。我们可以假设它是实现细节。

        2
  •  1
  •   Selman Genç    10 年前

    此报价来自 C# 5.0 Specification 7.8.4 Addition operator

    字符串串联:

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

    二进制文件的这些重载 + 运算符执行字符串 串联。如果字符串串联的操作数为空,则为空 字符串被替换。否则,将转换任何非字符串参数 通过调用虚拟ToString方法将其转换为字符串表示 从类型对象继承。如果ToString返回null,则为空字符串 被替换。

    我不知道为什么提到 超载,超载 虽然因为我们没有看到任何运算符重载。