4

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

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();
    }
}

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

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

谁能解释这种现象?

4

1 回答 1

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();
}
于 2012-08-10T18:10:06.720 回答