杜容 发表于 2023-4-3 18:07:48

IL阅读第二篇,拆箱装箱

            //装箱拆箱
            string name = "Zery";
            int age = 22;
            Console.WriteLine(age.ToString() + name);//已ToString的操作
            Console.WriteLine(age+name);//未ToString操作老规矩,一段C#,一段IL
        // Method begins at RVA 0x2050
        // Code size 48 (0x30)
        .maxstack 2
        .entrypoint
        .locals init (
                string name,
                int32 age
        )

        IL_0000: nop
        IL_0001: ldstr "Zery"
        IL_0006: stloc.0
        IL_0007: ldc.i4.s 22
        IL_0009: stloc.1
        IL_000a: ldloca.s age
        IL_000c: call instance string System.Int32::ToString()
        IL_0011: ldloc.0
        IL_0012: call string System.String::Concat(string, string)
        IL_0017: call void System.Console::WriteLine(string)
        IL_001c: nop
        IL_001d: ldloc.1
        IL_001e: box System.Int32
        IL_0023: ldloc.0
        IL_0024: call string System.String::Concat(object, object)
        IL_0029: call void System.Console::WriteLine(string)
        IL_002e: nop
        IL_002f: ret 
第一段:
IL_0000: nop以上的之前有过介绍,这次不做介绍
ldstr:推送对元数据中存储的字符串的新对象引用。
stloc.0加载到索引变量的第一位
ldc.i4.s:将位于特定索引处的局部变量的地址加载到计算堆栈上(短格式)。
stloc.1加载到索引变量的第二位
赋值之前一篇也讲过,这里不详细
       
        IL_000a: ldloca.s age
        IL_000c: call instance string System.Int32::ToString()
        IL_0011: ldloc.0
第二段:
ldloca.s :将位于特定索引处的局部变量的地址加载到计算堆栈上。
意思是将string类型的age变量,压入计算栈中
然后调用函数ToString,并将结果压入栈中
ldloc.0:将索引 0 处的局部变量加载到计算堆栈上。这样栈上就有两个了

        IL_0012: call string System.String::Concat(string, string)
        IL_0017: call void System.Console::WriteLine(string)
第三段:
栈弹出两个量,然后执行Concat,返回的值压入栈,
再弹出一个量,在执行WriteLine。

        IL_001c: nop
        IL_001d: ldloc.1
        IL_001e: box System.Int32
        IL_0023: ldloc.0
第四段:
Box:将值类转换为对象引用(O 类型)。
装箱box,先将第二个变量值压入计算栈,然后执行box装箱(填出栈,做box操作,返回值压入栈),再压入第一个变量的值

        IL_0024: call string System.String::Concat(object, object)
        IL_0029: call void System.Console::WriteLine(string)
        IL_002e: nop
        IL_002f: ret
第五段:
栈中弹出两个量执行Concat函数,返回值压入栈
栈中弹出一个量执行WriteLine
 

来源:https://www.cnblogs.com/RainbowInTheSky/archive/2023/04/03/4569144.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: IL阅读第二篇,拆箱装箱