gpt4 book ai didi

c# - string overload + operator 在哪里进行字符串连接?

转载 作者:太空狗 更新时间:2023-10-29 22:30:59 24 4
gpt4 key购买 nike

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

这个问题是从this提出的.很难向某人解释他不能使用 + 连接两个对象,因为如果 string 不关心重载运算符,object 不会重载此运算符要么。

最佳答案

String 不会重载 + 运算符。是 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 ,尽管它没有讨论对 String.Concat 的调用。我们可以假设它是实现细节。

关于c# - string overload + operator 在哪里进行字符串连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25622144/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com