本文介绍了结构和类对象数组的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天,我正在阅读C#参考,在那里我看到了一条声明.请看下面的语句.

Last day I was reading C# reference and there I saw a statement. Kindly have a look at the following statement.

上下文:

class Point
{
    public int x, y;
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
class Test
{
  static void Main() {
          Point[] points = new Point[100];
          for (int i = 0; i < 100; i++)
          points[i] = new Point(i, i*i);
      }
}
struct Point
{
     public int x, y;
     public Point(int x, int y) {
         this.x = x;
         this.y = y;
     }
}

问题:在这里,我的问题是在值类型"和引用类型"的情况下如何进行内存分配?

Question:Here my question is how memory allocation is done in case of Value Type and Reference Type?

困惑:为什么在《参考指南》中提到只能初始化1个对象.根据我对Array中每个对象的理解,将分配一个单独的内存.

Confusion:Why it is mentioned in Reference Guide that Only 1 Object will be intialized. As per my understanding for each object in Array a separate memory will be allocated.

修改:可能重复这个问题与jason建议的可能重复的问题有点不同.我关心的是仅在值类型和引用类型的情况下如何分配内存,而这个问题只是解释值类型和引用类型的概述.

Possible DuplicateThis question is bit different from possible duplicate question as suggested by jason. My concern is about how memory is allocated in case of Value Type and Referenece Type solely while that question just explain the overview of Value Type and Reference Type.

推荐答案

也许通过插图更容易理解引用类型的数组和值类型的数组之间的区别:

Perhaps the difference between an array of a reference type and an array of a value type is easier to understand with an illustration:

每个Point以及数组都在堆上分配,并且数组存储对每个Point的引用.总共需要N + 1个分配,其中N是点数.您还需要额外的间接访问权限来访问特定Point的字段,因为您必须通过引用.

Each Point as well as the array is allocated on the heap and the array stores references to each Point. In total you need N + 1 allocations where N is the number of points. You also need an extra indirection to access a field of a particular Point because you have to go through a reference.

每个Point直接存储在数组中.堆上只有一个分配.访问字段不涉及间接.可以直接从数组的内存地址,数组中项目的索引以及字段在值类型内部的位置直接计算出字段的内存地址.

Each Point is stored directly in the array. There is only one allocation on the heap. Accessing a field does not involve indirection. The memory address of the field can be computed directly from the memory address of the array, the index of the item in the array and the location of the field inside the value type.

这篇关于结构和类对象数组的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:05