翼度科技»论坛 编程开发 .net 查看内容

IL阅读第二篇,拆箱装箱

5

主题

5

帖子

15

积分

新手上路

Rank: 1

积分
15
  1.             //装箱拆箱
  2.             string name = "Zery";
  3.             int age = 22;
  4.             Console.WriteLine(age.ToString() + name);//已ToString的操作
  5.             Console.WriteLine(age+name);//未ToString操作
复制代码
老规矩,一段C#,一段IL
  1.         // Method begins at RVA 0x2050
  2.         // Code size 48 (0x30)
  3.         .maxstack 2
  4.         .entrypoint
  5.         .locals init (
  6.                 [0] string name,
  7.                 [1] int32 age
  8.         )
  9.         IL_0000: nop
  10.         IL_0001: ldstr "Zery"
  11.         IL_0006: stloc.0
  12.         IL_0007: ldc.i4.s 22
  13.         IL_0009: stloc.1
  14.         IL_000a: ldloca.s age
  15.         IL_000c: call instance string [mscorlib]System.Int32::ToString()
  16.         IL_0011: ldloc.0
  17.         IL_0012: call string [mscorlib]System.String::Concat(string, string)
  18.         IL_0017: call void [mscorlib]System.Console::WriteLine(string)
  19.         IL_001c: nop
  20.         IL_001d: ldloc.1
  21.         IL_001e: box [mscorlib]System.Int32
  22.         IL_0023: ldloc.0
  23.         IL_0024: call string [mscorlib]System.String::Concat(object, object)
  24.         IL_0029: call void [mscorlib]System.Console::WriteLine(string)
  25.         IL_002e: nop
  26.         IL_002f: ret
复制代码
 
第一段:
IL_0000: nop以上的之前有过介绍,这次不做介绍
ldstr:推送对元数据中存储的字符串的新对象引用。
stloc.0加载到索引变量的第一位
ldc.i4.s:将位于特定索引处的局部变量的地址加载到计算堆栈上(短格式)。
stloc.1加载到索引变量的第二位
赋值之前一篇也讲过,这里不详细
       
        IL_000a: ldloca.s age
        IL_000c: call instance string [mscorlib]System.Int32::ToString()
        IL_0011: ldloc.0
第二段:
ldloca.s :将位于特定索引处的局部变量的地址加载到计算堆栈上。
意思是将string类型的age变量,压入计算栈中
然后调用函数ToString,并将结果压入栈中
ldloc.0:将索引 0 处的局部变量加载到计算堆栈上。这样栈上就有两个了

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

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

        IL_0024: call string [mscorlib]System.String::Concat(object, object)
        IL_0029: call void [mscorlib]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】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具