4

私はこのコードを持っています (非常に優れたフレンドリーな Web サイトの場合)

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 に答える