装箱和拆箱会在阵列中发生吗? [英] Will Boxing and Unboxing happen in Array?

查看:114
本文介绍了装箱和拆箱会在阵列中发生吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,

按照 MSDN

装箱是将值类型转换为类型对象或该值类型实现的任何接口类型的过程.当CLR装箱值类型时,它将值包装在System.Object中,并将其存储在托管堆中.取消装箱从对象中提取值类型.装箱是隐式的;装箱是隐式的.拆箱是明确的.

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.

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

I knew We can store any objects in an arraylist, because system.object is a base for all all types. Boxing and unboxing happens in array list. I agree with that.

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

Will boxing and unboxing happens in an array? Because We can create object array like below

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

我是否了解装箱和拆箱是在这种阵列中进行的?

Is my understanding that boxing and unboxing happens in such array correct?

推荐答案

装箱和拆箱会在阵列中发生吗?

Will boxing and unboxing happens in an array?

数组本身已经是引用类型,数组本身没有装箱.但是,由于您的某些元素是值类型(intdoublechar),而您的数组类型是object,因此将对所述元素进行装箱.当您要提取它时,需要将其拆箱:

The Array itself is already a reference type, there is no boxing on the array itself. But, as some of your elements are value types (int, double and char), and your array type is object, a boxing will occur for the said element. When you'll want to extract it, you'll need to unbox it:

var num = (int)arr[0];

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

You can see it in the generated 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

这篇关于装箱和拆箱会在阵列中发生吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆