首页 文章

堆栈和堆和垃圾收集器

提问于
浏览
0

Headers 可能有点不正确,但它的Stack&Heap和Garbage Collector也是如此 .

我的代码:

static void Main(string[] args)
    {
        MyInt x = new MyInt();
        x.MyValue = 3;
        MyInt y = new MyInt();
        y = x;
        y.MyValue = 4;
        Console.Read();
    }

    public class MyInt
    {
        public int MyValue;
    }

我的问题:

我理解这是正确的,首先 y 创建时它的指针指向内存中的新 MyInt 然后 y 指针被 x 指针替换,现在 y 指向同一个对象(它被称为对象吗?)作为内存中的 x

那个 y 的对象现在已经创建了之前现在留在堆上没有指向它的任何指针?它存在于堆上但没有人指向内存中的这个对象 . 那现在这个对象是垃圾收集器?

我说得对吗?

2 回答

  • 1

    你是对的 . 好的是你可以通过使用 WeakReference 来证明它 .

    WeakReference 是跟踪另一个引用的对象,但不会阻止它被收集 . 这允许您随时检查目标引用,并查看它是否已被收集:

    private static void Main(string[] args)
    {
        MyInt x = new MyInt();
        x.MyValue = 3;
        MyInt y = new MyInt();
        WeakReference reference = new WeakReference(y);
        Console.WriteLine("Y is alive: " + reference.IsAlive);
        y = x;
        y.MyValue = 4;
        Console.WriteLine("Y is still alive: " + reference.IsAlive);
        Console.WriteLine("Running GC... ");
        GC.Collect(2);
        GC.WaitForFullGCComplete();
        Console.WriteLine("Y is alive: " + reference.IsAlive);
        Console.Read();
    }
    

    这段代码证明了你的观点,输出如下:

    Y is alive: True
    Y is still alive: True
    Running GC...
    Y is alive: False
    
  • 0

    是的,你的解释是正确的 . 首先,变量 xy 分别指向不同的值 - ab . 然后他们指向相同的值 a . 因此,没有对 b 的强引用,因此可以选择进行垃圾回收 .

相关问题