C# + operator calls string.concat function? [duplicate]

旧城冷巷雨未停 提交于 2019-12-22 06:25:14

问题


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);
    }

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

Thanks.


回答1:


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

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.

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.)

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.




回答2:


The code

    public string Foo(string str1, string str2)
    {
        return str1 + str2;
    }

gives the following IL:

IL_0000:  nop
IL_0001:  ldarg.1
IL_0002:  ldarg.2
IL_0003:  call       string [mscorlib]System.String::Concat(string, string)
IL_0008:  stloc.0
IL_0009:  br.s       IL_000b
IL_000b:  ldloc.0
IL_000c:  ret

The compiler (at least, the one in Visual Studio 2010) does this job and there is no + overloading.



来源:https://stackoverflow.com/questions/13617707/c-sharp-operator-calls-string-concat-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!