装箱与拆箱学习笔记

class DllTestClientApp
{
 public static void Main()
 {
  int iage = 40;
  object objage = iage;

  int iold = (int)objage;
 }
}

生成的IL代码如下:

.method public hidebysig static void  Main () cil managed

{

  .entrypoint

  // 代码大小       19 (0x13)

  .maxstack  1

  .locals init (int32 V_0,

           object V_1,

           int32 V_2)                                                     //参数列表, 分别对应变量iage, objage, iold

  IL_0000:  ldc.i4.s   40                                            //40压入堆栈

  IL_0002:  stloc.0                                                   //弹出堆栈内容给第一个参数, V_0(iage)

  IL_0003:  ldloc.0                                                   //将第一个参数压入堆栈(生成副本,性能损失)

  IL_0004:  box        [mscorlib]System.Int32          //装箱:分配对象内存à赋值à地址压入堆栈

  IL_0009:  stloc.1                                                   //弹出堆栈内容给第二个参数, V_1(objage)

  IL_000a:  ldloc.1                                                   //将第二个参数压入堆栈(地址)

  IL_000b:  unbox      [mscorlib]System.Int32        //拆箱:检查地址是否有效à返回对象内值的指针

  IL_0010:  ldind.i4                                                  //取得堆栈中的指针指向的值, 然后压入堆栈

  IL_0011:  stloc.2                                                   //弹出堆栈内容给第三个参数, V_2(iold)

  IL_0012:  ret                                                         //返回

} // end of method DllTestClientApp::Main

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值