【发布时间】:2012-11-29 02:04:58
【问题描述】:
我刚刚发现我们写了这样一行:
string s = "string";
s = s + s; // this translates to s = string.concat("string", "string");
但是我通过反射器打开了字符串类,我没有看到这个 + 运算符在哪里重载?我可以看到 == 和 != 被重载了。
[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);
}
那么当我们使用 + 组合字符串时,为什么会调用 concat 呢?
谢谢。
【问题讨论】:
-
@MichaelPetrotta 这不是那个问题的重复。链接的问题实际上涉及常量折叠。
-
@phoog,好吧,我有点同意你的观点,因为问题没有涵盖这一点,但 Jon 的回答准确地回答了 VVV 的问题。
-
@MichaelPetrotta,J. Skeet 的回答如何回答这个问题?
-
如果两个字符串被键入为
dynamic,运行时是否硬编码将添加处理为String.Concat? -
@MichaelPetrotta 抱歉,我一直不清楚。我试图强调一个事实,即当前问题的答案是“第 7.7.4 节”,但乔恩对假定重复问题的回答是“第 7.18 节”。 Jon 的回答和问题是关于常量折叠,而不是 + 运算符的定义。这个问题是关于 + 运算符的定义。事实上,这两个问题的共同答案是“编译器会这样做”,但如果我们在规范中寻找“为什么”问题的答案,那么答案就会不同,而且问题不会重复。
标签: c# string operator-overloading concatenation