<分区>
所以我有一个简单的 Bell 类,我正在其上测试垃圾收集:
public class Bell
{
public void Ring()
{
Console.WriteLine("Ding ding");
}
}
如果我在下面运行这段代码,它不会被垃圾回收
class Program
{
private static WeakReference reference;
private static void Main()
{
Console.WriteLine("Starting");
var bell = new Bell();
reference = new WeakReference(bell);
bell = null;
GC.Collect();
Console.WriteLine("Object still alive: {0}", reference.IsAlive);
if (reference.Target == null)
{
Console.WriteLine("Bell is no more!");
}
else
{
{
var theBell = (Bell)reference.Target;
theBell.Ring();
}
}
Console.ReadLine();
}
}
如果我只检查 reference.IsAlive 如下所示,它是垃圾收集
class Program
{
private static WeakReference reference;
private static void Main()
{
Console.WriteLine("Starting");
var bell = new Bell();
reference = new WeakReference(bell);
bell = null;
GC.Collect();
Console.WriteLine("Object still alive: {0}", reference.IsAlive);
Console.ReadLine();
}
}
你们能给我解释一下这是如何工作的吗?