【问题标题】:Another C# question about references/collections/value types关于引用/集合/值类型的另一个 C# 问题
【发布时间】:2010-10-03 11:25:30
【问题描述】:

我有以下代码:

public class Test
{
    public static void Main()
    {
        List<Person> list = new List<Person>();
        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 个问题)。

【问题讨论】:

    标签: c# .net stack heap-memory


    【解决方案1】:

    1) 它在堆上(如果 > 84K 则在大对象堆上)

    2) 是的,创建了一个新实例。可以通过列表访问来引用。

    3) 集合可能使用列表,但您不需要知道内部细节,除非您需要特定的速度或空间属性。

    【讨论】:

    • 在方法完成之前,Person person... 在堆栈上?我的问题更多的是关于通用列表而不是旧的堆栈/堆列表
    【解决方案2】:
        List<Person> list = new List<Person>();
    
        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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      • 1970-01-01
      相关资源
      最近更新 更多