微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/csharp/95941.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐