堆栈&堆&垃圾收集器

时间:2013-12-12 09:09:10

标签: c# stack heap garbage

标题可能有点不正确,但它关于Stack&不过,堆和垃圾收集器一样。

我的代码:

    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指针替换为现在{ {1}}在内存中指向同一个对象(它被称为对象吗?)为y

那个x现在创建的对象现在已经在堆上了,没有指向它的指针?它存在于堆上但没有人指向内存中的这个对象。现在这个对象是垃圾收集器的主题吗?

我说得对吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

相关问题