C# 对象引用另一个对象的 属性

C# Object reference to another object's property

假设我有一个对象的 属性 在其生命周期中指向不同的对象。

MyClassInstance.MyProperty = MyOtherObject1;

稍后在应用程序中我得到这个:

MyClassInstance.MyProperty = MyOtherObject2;

等等。我的理解是 MyOtherObject1 和 MyOtherObject2 将指向内存中的相同地址,我想避免这种情况。如何确保 MyOtherObject1 和 MyotherObject2 是 2 个完全不同的实体?

如果MyOtherObject1MyOtherObject2是不同的对象,使MyClassInstance.MyProperty等于它们,不会导致这2个相同。

MyClassInstance.MyProperty = MyOtherObject1;

这意味着对 MyClassInstance.MyProperty 的任何更改都会更改 MyOtherObject1,因为它们实际上指向相同的内存 space。

MyClassInstance.MyProperty = MyOtherObject2;

这意味着 MyProperty 现在指向与 MyOtherObject2 相同的内存 space。对 MyProperty 的更改将使 MyOtherProperty1 不受影响。