简体   繁体   English

为阵列分配内存

[英]Allocation of memory for an Array

All types are derived from the Object class, but the value types aren't allocated on the heap. 所有类型都是从Object类派生的,但是值类型没有在堆上分配。 Value type variables actually contain their values. 值类型变量实际上包含它们的值。 so how then can these types be stored in arrays and used in methods that expect reference variables ? 那么如何将这些类型存储在数组中并用于需要引用变量的方法中? Can somebody please explain me how these value types are stored on heap when they are part of an array? 有人可以解释一下这些值类型是数组的一部分时如何将它们存储在堆中吗?

Boxing and Unboxing . 装箱和拆箱 Also see Here for info pertaining to arrays specifically (part way down). 另请参阅此处,以获得与阵列有关的信息(部分下降)。 Note this is for object arrays, a valuetype array (eg int[] ) doesn't have any (un)boxing. 请注意,这是针对对象数组的,值类型数组(例如int[] )没有任何(un)装箱。

Have a look at this question: 看一下这个问题:

Arrays, heap and stack and value types 数组,堆和堆栈以及值类型

You can pass the instance of a value type to a method expecting an object (ref class). 您可以将值类型的实例传递给需要对象的方法(引用类)。 In this case boxing and unboxing happens. 在这种情况下,发生装箱和拆箱。

Value type arrays do not require boxing or unboxing! 值类型数组不需要装箱或拆箱!

The CLR handles arrays of value types specially. CLR特别处理值类型的数组。 Of course an array is a reference type which is allocated on the heap, but the value type values are embedded into the heap record (not on the stack). 当然,数组是在堆上分配的引用类型,但是值类型的值将嵌入到堆记录中(而不是在堆栈中)。

Similarly, when a reference type class contains a value type field, the value of the field is embedded into the record on the heap.. 同样,当引用类型类包含值类型字段时,该字段的值将嵌入到堆中的记录中。

Value types may be allocated on stack. 值类型可以在堆栈上分配。 This can happen only if they are in parameters or local variables or fields in a another value type which is. 仅当它们在参数,局部变量或其他值类型的字段中时,才可能发生这种情况。

Value types in arrays and fields in classes are stored locally in array or class, instead of pointer being stored there - value types result in more local memory access (performance improvement) and in case of arrays value n is right after value n-1 in memory, something which is not guaranteed with objects in array of reference types (including boxed values in array of object - also no grantee of continuity). 数组中的值类型和类中的字段存储在本地数组或类中,而不是将指针存储在其中;值类型导致更多的本地内存访问(性能提高),并且在数组的情况下,值n紧接在值n-1之后内存,这是引用类型数组中的对象不能保证的(包括对象数组中的框式值-也不具有连续性)。 In arrays of reference types it is the references that are continual. 在引用类型数组中,引用是连续的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM