问题
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:
回答1:
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:
- objectA
- objectA.AList
- objectA.AList[0]
- objectA.AList[1]
- 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.
来源:https://stackoverflow.com/questions/37293387/how-is-memory-allocated-when-you-create-a-property-of-class