IL笔记

初识

    // C#
    strA = "值A";
    string strB = "值B";
    Console.WriteLine(strA);

    // IL:
    // [8 9 - 8 10]
    IL_0000: nop

    // [9 13 - 9 32]
    IL_0001: ldstr        "值A"
    IL_0006: stloc.0      // strA

    // [10 13 - 10 32]
    IL_0007: ldstr        "值B"
    IL_000c: stloc.1      // strB

    // [11 13 - 11 37]
    IL_000d: ldloc.0      // strA
    IL_000e: call         void [System.Console]System.Console::WriteLine(string)
    IL_0013: nop

解析:


string strA = "值A";   // 对应:     
IL_0001: ldstr        "值A"  // 把常量值 "值A" 存入评价堆栈 
IL_0006: stloc.0      // strA // 从评价堆栈中取出一个值保存到当前方法的第一个变量(.0)
// 此时评价堆栈中无值,本地变量strA 值为"值A"

string strB = "值B"; //同上

Console.WriteLine(strA); 对应:
IL_000d: ldloc.0      // strA // 读取当前方法的第一个变量(.0)存入评价堆栈
IL_000e: call         void [System.Console]System.Console::WriteLine(string) // 调用cw方法参数为 堆栈内值


// 可以验证下是否正确
// 把上述 Console.WriteLine(strA); 改为 Console.WriteLine(strA + strB + strA);
/* 此时猜想一下   
* 1:读取当前方法第一个变量(strA序号为0) 放入评价堆栈 
* 2: 读取当前方法第二个变量(strB 序号为1) 放入评价堆栈 
* 3:读取当前方法第一个变量(strA序号为0) 放入评价堆栈 
* 此时评价堆栈中值有3个   0:"值A",1:"值B",2:"值A" IL 如下:
*/

   // [11 13 - 11 51] 
    IL_000d: ldloc.0      // strA
    IL_000e: ldloc.1      // strB
    IL_000f: ldloc.0      // strA
    IL_0010: call         string [System.Runtime]System.String::Concat(string, string, string)
    IL_0015: call         void [System.Console]System.Console::WriteLine(string)
    IL_001a: nop
原文地址:https://www.cnblogs.com/caiyangcc/p/13961487.html