C#垃圾收集器Ressurection NullRefException

use*_*444 4 c# garbage-collection

我有这个代码(用于一个非常好的和友好的网站)

public class B
{
    static public A IntA;
}

public class A
{
    private int x;

    public A(int num)
    {
        x = num;
    }

    public void Print()
    {
        Console.WriteLine("Value : {0}", x);
    }

    ~A()
    {
        B.IntA = this;
    }
}

class RessurectionExample
{
    // Ressurection
    static void Main()
    {
        // Create A instance and print its value
        A a = new A(50);
        a.Print();

        // Strand the A object (have nothing point to it)
        a = null;

        // Activate the garbage collector
        GC.Collect();

        // Print A's value again
        B.IntA.Print();
    }
}
Run Code Online (Sandbox Code Playgroud)

它创建一个值为50的A实例,打印它,通过将其唯一的引用设置为null来链接创建的对象,激活他的Dtor并在保存到B之后再次打印它.

现在,奇怪的是当调试时,当光标指向最后一行(B.IntA.Print())时,静态A成员的值为null,按下F10后,我得到一个NullReferenceException,但是静态A成员更改为应该是什么.

谁能解释这个现象?

Ree*_*sey 7

您需要调用GC.WaitForPendingFinalizers.如果没有这个,你的析构函数实际上不会被按顺序调用.

static void Main()
{
    // Create A instance and print its value
    A a = new A(50);
    a.Print();

    // Strand the A object (have nothing point to it)
    a = null;

    // Activate the garbage collector
    GC.Collect();

    // Add this to wait for the destructor to finish
    GC.WaitForPendingFinalizers();

    // Print A's value again
    B.IntA.Print();
}
Run Code Online (Sandbox Code Playgroud)