C #In general, we think"+" OperatorThere are 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 ); |