加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:18:13 所属栏目:百科 来源:网络整理
导读:我是新来的编程, 根据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
我是新来的编程,

根据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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读