In C #, we generally think that the "+" operator has two functions: arithmetic addition and string connection.
Today, I saw a document saying that I had to thoroughly analyze the different operations performed by the two plus operators in C #. I thought it was the case, this is also true for IL code instances:
Let's write a short test code:
Namespace msiltest
{
Class Program
{
Static void main (string [] ARGs)
{
String A = "AAA ";
String B = a + "BBB ";
System. Console. writeline (B );
Int c = 1;
Int d = C + 1;
System. Console. writeline (d );
}
}
}
Decompile to obtain the Il code:
. Method private hidebysig static void main (string [] ARGs) cel managed
{
. Entrypoint
// Code size 40 (0x28)
. Maxstack 2
. Locals Init ([0] string,
[1] string B,
[2] int32 C,
[3] int32 D)
Il_0000: NOP
Il_0001: ldstr "AAA"
Il_0006: stloc.0
Il_0007: ldloc.0
Il_0008: ldstr "BBB"
Il_000d: Call string [mscorlib] system. String: Concat (string,
String)
Il_0012: stloc.1
Il_0013: ldloc.1
Il_0014: Call void [mscorlib] system. Console: writeline (string)
Il_0019: NOP
Il_001a: LDC. i4.1
Il_001b: stloc.2
Il_001c: ldloc.2
Il_001d: LDC. i4.1
Il_001e: add
Il_001f: stloc.3
Il_0020: ldloc.3
Il_0021: Call void [mscorlib] system. Console: writeline (int32)
Il_0026: NOP
Il_0027: Ret
} // End of method program: Main
From the code above, we can see that C #'s complier converts it into a Concat () function with two parameters when connecting strings. This function can decompile system. DLL to see the static method with two parameters.
While + is directly converted into the add operation command when handle has two numbers.
There is nothing similar to the two operation commands. Therefore, we need to treat the two + functions as two operators.
At the same time, we can also extend it to some extent, about the forced type conversion in C:
Let's take a look at this sentence:
Il_0021: Call void [mscorlib] system. Console: writeline (int32)
If we set
System. Console. writeline (d );
Change
System. Console. writeline ('\ u0041 ');
The corresponding il code will be changed:
Il_0020: LDC. i4.s 65
Il_0022: Call void [mscorlib] system. Console: writeline (char)
Therefore, we can draw a conclusion:
Forced type conversion only calls different overload methods of some methods, and the value itself remains unchanged.
This value remains unchanged at the top of the stack, except that the compiler selects different overloaded versions of different methods based on the Code for forced type conversion.
Trace the value at the top of the stack. The result also supports our conclusion.