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

前端之家收集整理的这篇文章主要介绍了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是所有类型的基础.数组列表中发生装箱和拆箱.我同意这一点.

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

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

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

解决方法

Will Boxing and unBoxing happens in an array?

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

  1. var num = (int)arr[0];

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

  1. IL_0000: ldarg.0
  2. IL_0001: ldc.i4.4
  3. IL_0002: newarr [mscorlib]System.Object
  4. IL_0007: dup
  5. IL_0008: ldc.i4.0
  6. IL_0009: ldc.i4.1
  7. IL_000a: Box [mscorlib]System.Int32 // Boxing of int
  8. IL_000f: stelem.ref
  9. IL_0010: dup
  10. IL_0011: ldc.i4.1
  11. IL_0012: ldstr "abc"
  12. IL_0017: stelem.ref
  13. IL_0018: dup
  14. IL_0019: ldc.i4.2
  15. IL_001a: ldc.i4.s 99
  16. IL_001c: Box [mscorlib]System.Char
  17. IL_0021: stelem.ref
  18. IL_0022: dup
  19. IL_0023: ldc.i4.3
  20. IL_0024: ldc.r8 12.25
  21. IL_002d: Box [mscorlib]System.Double
  22. IL_0032: stelem.ref
  23. IL_0033: stfld object[] C::arr
  24. IL_0038: ldarg.0
  25. IL_0039: call instance void [mscorlib]System.Object::.ctor()
  26. IL_003e: nop
  27. IL_003f: ret

猜你在找的C#相关文章