在创建类的属性时如何分配内存? [英] How is memory allocated when you create a property of class?

查看:218
本文介绍了在创建类的属性时如何分配内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  public class A 
{
public List< string> AList {get;组; }
}

然后我创建一个类的对象:

  A objectA = new A(); 
objectA.AList = new List< string>(){1,2,3};

我的问题是如何将内存分配到堆中?我的意思是将 objectA.AList 分配给 objectA (image1)或作为堆中单独的对象(image2 )

imgur.com/M6vIU.pngrel =nofollow noreferrer>



Image2:

解决方案

正确的答案是:图片3. 我不打算画这个,但是您的示例将导致堆上的5个对象。



对象(实例)没有名称,但它们被以下引用引用:


$ b


  1. objectA

  2. objectA.AList

  3. objectA.AList [0] li>
  4. objectA.AList [1]

  5. objectA.AList [2] li>

每个字符串也是一个对象。


$ b $ < objectA 实例只包含对List的引用,List包含对字符串的引用数组。 3被使用,更多可能被分配,仍然是 null




I have the following class:

public class A
{
    public List<string> AList { get; set; }
}

Then I create object of a class:

A objectA = new A();
objectA.AList = new List<string>() { "1", "2", "3" };

My question is how memory will be allocated in a heap? I mean will be objectA.AList allocated inside of objectA (image1) or as a separate object in a heap(image2)

Image1:

Image2:

解决方案

The correct answer is : Image 3.

I'm not going to draw this but your example leads to 5 objects on the Heap.

Objects (instances) don't have names but they are referred to by the following references:

  1. objectA
  2. objectA.AList
  3. objectA.AList[0]
  4. objectA.AList[1]
  5. objectA.AList[2]

Each string is also an object on its own.

The objectA instance only contains a reference to the List, and the List holds an array of references to strings. 3 are used, more might be allocated and still be null.

None of these objects lives 'inside' another.

这篇关于在创建类的属性时如何分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆