我最近浏览了一篇垃圾收集文章并决定一起玩,并试图获得更多的理解.我编写了以下代码,玩弄了using声明,但对结果感到惊讶......我期望在使用块之外的e.Parent.Name会变成ka-blooey.
到底发生了什么?
static void Main(string[] args)
{
Employee e = new Employee();
using (Parent p = new Parent())
{
p.Name = "Betsy";
e.Parent = p;
Console.WriteLine(e.Parent.Name);
}
Console.WriteLine(e.Parent.Name);
Console.ReadLine();
}
public class Employee
{
public Parent Parent;
}
public class Parent : IDisposable
{
public string Name;
public void Dispose()
{
Console.WriteLine("Disposing Parent");
}
}
Run Code Online (Sandbox Code Playgroud)