前端之家收集整理的这篇文章主要介绍了
c# – 将会在Array中发生Boxing和Unboxing吗?,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
403_0@@H_
404_1@我是新来的编程,
根据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