请看下面的代码:
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();
}
}
我希望此代码崩溃,但事实并非如此。
为什么?
那不是引用的工作方式。
Child child1 = new Child();
创建对新对象的引用Child
Child child2 = child1;
创建另一个引用,指向同一个对象child1
呢
child1 = null;
将child1
引用设置为null
(不再指向任何内容)。它不会更改它指向的对象并且不会影响child2
。child2
仍然指向它之前所做的同一对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句