当前位置:  开发笔记 > 编程语言 > 正文

关于引用/集合/值类型的另一个C#问题

如何解决《关于引用/集合/值类型的另一个C#问题》经验,为你挑选了1个好方法。

我有以下代码:

public class Test
{
    public static void Main()
    {
        List list = new List();
        Person person = new Person() { Name="Chris" };
        list.Add(person);

        person = new Person(){ Name="Wilson the cat" };
        list.Add(person);

        Console.WriteLine(list[0].Name);
        Console.WriteLine(list[1].Name);
        Console.ReadLine();
    }
}

public class Person
{
    public string Name {get;set;}   
}

我的问题是第一人称实例去了哪里?CLR是否在某处神奇地创建了它的新实例?无论如何在列表之外引用它 - 例如,在方法完成后它会去哪里?用于在集合中存储对象的方法(这是4个问题).



1> Juliet..:
    List list = new List();

    Person person = new Person() { Name="Chris" };
    // your person object lives on the heap. The person variable is just
    // a pointer of that object on the heap. Note that the pointer lives
    // on the stack, and the object it points to lives on the heap.

    list.Add(person);
    // when you add your person to to the list, all it does it pass a
    // copy of the *pointer* to the list's method. List has access to this
    // object through the pointer.

    person = new Person(){ Name="Wilson the cat" };
    // new'ing up a instance of person creates another person object on
    // the heap. Note that this doesn't overwrite our original person created above,
    // because our original person sits in an entirely differently memory 
    // location.

    // We did, however overwrite our pointer variable by assigning it a new
    // location to point at. This doesn't affect the object we put into our
    // list since the list received a copy of our original pointer :)

    list.Add(person);

    Console.WriteLine(list[0].Name);
    // list[0] has a pointer to the first object we created


    Console.WriteLine(list[1].Name);
    // list[1] has a pointer to the second object we created.

    Console.ReadLine();

    // when this methods goes out of scope (i.e. when the stack frame is
    // popped), the pointers will be dropped from memory, and the objects
    // on the heap will no longer have any live references to them, so
    // they'll be eaten by the garbage collector.

推荐阅读
手机用户2402851155
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有