我有一个类定义如下:类的对象副本的引用,其中作为.NET对象复制价值
class foo
{
private string _bar;
public string Bar
{
get { return _bar; }
set { _bar = value; }
}
}
查看以下操作:
foo myFoo = new foo();//Creating an object of foo
myFoo.Bar = "sample";//assign value for bar
foo currentFoo = myFoo;//Assign the object to another object
currentFoo.Bar = "newValue";//Change the value of newly created object.
在这种情况下,后bar
这两个对象的最终步值将变为newValue
,其中对象(.net)类型的值不会像这样反映:
object obj = "currentValue";//assign some value
object newObj = obj;//assign object to another object
newObj = "Changed Value";//change the value of new object.
为什么没有更新旧对象的值?原因是什么?是否有可能创建类的对象像这样?
更新:
我已经检查了以下情形太:
foo myFoo = new foo();
myFoo.Bar = "sample";
object currentFoo = myFoo;
((foo)currentFoo).Bar = "newValue";
//Here also both the objects get updated.
字符串是不可变的。你的例子类不是。 – Phylogenesis
它们也有些作为值类型,比如'int'(因为它们是不可变的)。 –
@unlucky,你误解了一些东西,这一行newObj =“改变了值”;将创建一个新的字符串对象而不改变现有对象的值 – Kira