请看下面的代码:
class Parent{}
class Child : Parent
{
public int field
{
get;
set;
}
}
class Program
{
static void Main(string[] args)
{
Child child1 = new Child();
Child child2 = child1; //same memory address?
child1.field = 12;
child2.field = 14;
Console.WriteLine(child1.field); //14, as expected
child1 = null;
Console.WriteLine(child2.field); //expected to crush: 'child1' is null so expected 'child2' to also be null
Console.ReadLine();
}
}
我以为这段代码会崩溃,但它却没有。
为什么呢?
null
不会销毁它所指向的对象。只有当没有更多的引用并且垃圾回收运行时,对象才会被销毁(垃圾回收)。 - Matt Burlandchild1 = null;
实际上是想用child1.Dispose();
吧? - Batu.Khan