我有这段代码(用于一个非常好的和友好的网站)
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 实例,打印它,通过将他的唯一引用设置为空来将创建的对象串起来,激活他的 Dtor 并在保存在 B 之后 - 再次打印它。
现在,奇怪的是,在调试时,当光标指向最后一行(B.IntA.Print())时,静态 A 成员的值为 null,按 F10 后,我得到一个 NullReferenceException BUT静态 A 成员的值更改为应有的值。
谁能解释一下这个现象?
最佳答案
您需要调用 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();
}
关于C# 垃圾收集器复活 Null Ref 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11906984/