让我们遍历每一行:
myObject bob; // Creates a variable of type myObject, but it doesn't point anywhere
bob = new myObject(); // bob now points to a newly created myObject instance
myObject joe; // Creates a variable of type myObject, but it doesn't point anywhere
joe = bob; // joe now refers to the same object as bob
要记住的重要一点是,最后一行复制了引用本身的值。比如如果bob
指向地址1000,joe
也会指向那里。因此,如果您更改此地址的任何数据,两者joe
和bob
都将指向相同的数据。
但是,欢迎您设置joe
指向其他地方,它不会影响bob
. 换句话说:
joe = null; // This will not null out bob
如果你想创建一个全新的实例myObject
,你必须这样做:
joe = new myObject(); // This will also not affect bob
现在,如果您尝试myObject
在内存中创建一个新实例并复制现有实例的所有属性,您必须自己执行此操作:
joe = new myObject();
joe.X = bob.X; // Assuming X is not a reference itself
joe.Y = bob.Y; // ...or you'd have to do this recursively
.NET 不提供为您进行此复制的方法。一种常见的模式是为它创建一个构造函数,myObject()
它接受一个实例myObject
并复制其所有属性:
joe = new myObject(bob);