考虑以下代码:
class Program
{
static void Main(string[] args)
{
A a = new A();
CreateB(a);
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("And here's:" + a);
GC.KeepAlive(a);
}
private static void CreateB(A a)
{
B b = new B(a);
}
}
class A
{ }
class B
{
private WeakReference a;
public B(A a)
{
this.a = new WeakReference(a);
}
~B()
{
Console.WriteLine("a.IsAlive: " + a.IsAlive);
Console.WriteLine("a.Target: " + a.Target);
}
}
使用以下输出:
a.IsAlive: False
a.Target:
And here's:ConsoleApp.A
为什么它是假的和空的?A 还没有被收集到。
编辑:哦,你的小信仰。
我添加了以下几行:
Console.WriteLine("And here's:" + a);
GC.KeepAlive(a);
查看更新的输出。