c# – 将会在Array中发生Boxing和Unboxing吗?

我是新来的编程,

根据MSDN,

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR Boxes a value type,it wraps the value inside a System.Object and stores it on the managed heap. UnBoxing extracts the value type from the object. Boxing is implicit; unBoxing is explicit.

我知道我们可以将任何对象存储在数组列表中,因为system.object是所有类型的基础.数组列表中发生装箱和拆箱.我同意这一点.

拳击和拆箱会发生在阵列中吗?因为我们可以像下面那样创建对象数组

object[] arr = new object[4] { 1,"abc",'c',12.25 };

我的理解是,拳击和拆箱发生在这样的阵列正确吗?

解决方法

Will Boxing and unBoxing happens in an array?

阵列本身已经是一个引用类型,阵列本身没有拳击.但是,由于您的某些元素是值类型(int,double和char),并且您的数组类型是对象,所以元素将发生拳击.当你想要解压它,你需要取消选择它:

var num = (int)arr[0];

您可以在生成的IL中看到它:

IL_0000: ldarg.0
IL_0001: ldc.i4.4
IL_0002: newarr [mscorlib]System.Object
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: Box [mscorlib]system.int32 // Boxing of int
IL_000f: stelem.ref
IL_0010: dup
IL_0011: ldc.i4.1
IL_0012: ldstr "abc"
IL_0017: stelem.ref
IL_0018: dup
IL_0019: ldc.i4.2
IL_001a: ldc.i4.s 99
IL_001c: Box [mscorlib]System.Char
IL_0021: stelem.ref
IL_0022: dup
IL_0023: ldc.i4.3
IL_0024: ldc.r8 12.25
IL_002d: Box [mscorlib]System.Double
IL_0032: stelem.ref
IL_0033: stfld object[] C::arr
IL_0038: ldarg.0
IL_0039: call instance void [mscorlib]System.Object::.ctor()
IL_003e: nop
IL_003f: ret

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...