首页 > 解决方案 > 当仍然引用它的对象字段时,C# 对象有资格进行垃圾回收吗?

问题描述

using System.Collections.Generic;

public class A
{
    private int[] someothersubmemory;
    private List<int> b;

    public A ()
    {
        b = new List<int> ();
        someothersubmemory = new int[1000000];
    }

    public List<int> getList ()
    {
        return b;
    }
}


// elsewhere:

A a = new A();
List<int> c = a.getList();
a = null;                    // assume all references to the A() itself created 2 lines above are gone

我受过关于垃圾收集是一种自动处理释放内存的教育。

  1. 但是,当仍然存在对相关内存的某些“子内存”的引用时,垃圾收集(在 C# 中)是否也注意不释放内存?在上面的例子中,内存是 A(),子内存是 A() 中的 b,现在由 c 引用。

  2. 如果 C# GC 或 C#/.NET 的其他部分确实在仍有引用时不释放(子)内存,那么上述示例的“someothersubmemory”何时被释放?当不再引用 A() 或不再引用其他子内存时(即不再引用 b )?

标签: c#.netgarbage-collection

解决方案


推荐阅读