【发布时间】:2020-02-12 19:45:11
【问题描述】:
我有以下 C# 代码。
SomeObject myObject = new SomeObject();
SomeObject anotherObject = new SomeObject();
anotherObject = myObject;
如果我修改 myObject,anotherObject 会被修改。 有什么办法可以解开它们吗? 比如:
Object.unbind(myObject, anotherObject);
这样修改 myObject 不会影响 anotherObject?
【问题讨论】:
-
没有,但你可能想使用一些克隆或复制机制,c#中有很多这样的机制
-
你为什么要这样做呢?
-
@IanKemp 长混淆代码,Object.ReferenceEquals(myObject, anotherObject) 返回 true。不知道那是怎么发生的。需要修改 myObject 而不改变 anotherObject。
-
发生的事情是您放弃了第二个实例,并将第二个变量指向第一个变量引用的实例。
-
anotherObject不是对象,它是对对象的引用。在第一次赋值(初始化)之后,它指向与myObject不同的对象。第二次赋值后,myObject和anotherObject都指向同一个对象。考虑:将myObject重命名为refToMyObject,将anotherObject重命名为refToASomeObject。是不是更清楚了?
标签: c# pass-by-reference