由另一个集合分配的集合是否会在内存中增长

时间:2015-03-26 21:04:04

标签: c#

我有以下代码:

class Program
{
    static void Main(string[] args)
    {
        List<string> mylist= new List<string>();
        mylist.Add("a");
        mylist.Add("b");
        mylist.Add("c");


        B b = new B(mylist);
        b.Add();
        Console.WriteLine(mylist.Count.ToString()); //Output 4


    }
}

class B
{
    public List<string> mylist2 { get; set; }
    public B(List<string> lsarg)
    {
        mylist2 = new List<string>(); //new allocate new location?
        mylist2 = lsarg;
    }
    public void Add()
    {
        mylist2.Add("hi");
    }
}

据我所知,在B类构造函数中我没有复制lsarg列表,这就是为什么在行中

mylist2=lsarg;

myList2和lsarg是相同的列表 我的问题是,如果我添加mylist列表新项目,B对象中的mylist2会长大吗?我的意思是它会在B对象的内存中长大吗?

1 个答案:

答案 0 :(得分:2)

是的,您的变量mulistmylist2都指向List<>的相同引用。

mylistmylist2只是(32 | 64)位内存指针,指向存储实际List<>对象的位置。

这是类型与参考类型之间的区别。

List<>是参考类型。

e.g。

List<string> mylist= new List<string>();

可以这样解释;

List<string> mylist;
// Creates a new variable mylist at location (0x1) which points to a List<string> (currently null)

mylist = new List<string>();
// Creates a new List<String> in memory location A
// and assigns variable mylist (0x1) to (0xA) which is where this new list is located

然后当你构建B:

new B(mylist);
// Calls constructor of B passing in the same reference that mylist holds. (0xA)

B的内部构造函数

List<string>() mylist2;
// Creates a new variable mylist2 at location 2 which points to a List<string> (currently null)

mylist2 = new List<string>(); 
// Creates a new List<String> in memory location B
// and assigns variable mylist (0x2) to (0xB) which is where this new list is located

mylist2 = lsarg;
// Assigns the passed in reference (0xA) to mylist2 (0x2), therefore pointing to the same place.
// Add this point the previous created list (0xB) no longer has any pointers to it.
// and will get Garbage Collected once GC runs.

你的记忆看起来像这样:

Location    Size    Value
[0x1]       32      [0xA] <-- Pointer
[0x2]       32      [0xA] <-- Pointer   
[...]
[0xA]       x       List<string>
[0xB]               List<string> <-- This has no pointer anymore, will get GC'ed