C#+运算符调用string.concat函数吗? [英] C# + operator calls string.concat function?

查看:115
本文介绍了C#+运算符调用string.concat函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
C#是否优化字符串文字的串联?

Possible Duplicate:
Does C# optimize the concatenation of string literals?

我刚刚发现我们这样写一行:

I just found out that we write a line like this:

string s = "string";
s = s + s; // this translates to s = string.concat("string", "string");

但是,我通过反射器打开了字符串类,但看不到该+运算符在哪里重载?我可以看到==和!=超载.

However I opened the string class through reflector and I don't see where this + operator is overloaded? I can see that == and != are overloaded.

[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?

So why does concat gets called when we use + for combining strings?

谢谢.

推荐答案

那么为什么在使用+组合字符串时为什么会调用concat?

So why does concat gets called when we use + for combining strings?

C#规范的7.7.4节加法运算符"定义了字符串的二进制加法运算符,其中该运算符返回操作数的串联.

Section 7.7.4 of the C# specification, "Addition operator", defines a binary addition operator for strings, where the operator returns the concatenation of the operands.

CLI规范中的System.String定义包括多个Concat重载,但没有+运算符. (我没有明确的答案来解释这种遗漏,但我想是因为某些语言为字符串连接定义了+以外的其他运算符.)

The definition of System.String in the CLI specification includes several Concat overloads, but no + operator. (I don't have a definitive answer explaining that omission, but I suppose it's because some languages define operators other than + for string concatenation.)

鉴于这两个事实,C#编译器编写程序最合乎逻辑的解决方案是在编译+(string, string)运算符时发出对String.Concat的调用.

Given these two facts, the most logical solution for the C# compiler writer is to emit a call to String.Concat when compiling the +(string, string) operator.

这篇关于C#+运算符调用string.concat函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆