C#更新对象属性而不破坏实例

时间:2010-01-16 06:32:42

标签: c#

我想一次更新具有新创建对象属性的实例,但不要破坏与其他变量绑定的实例。例如。

public class MyClass{
   public double X;
   public double Y;
}

MyClass a = new MyClass(2,1);
MyClass b = a;

MyClass c = new MyClass(1,1);

a = c; //'b' should also be equal to 'a'.
//I dont want to do something like this:
a.Y = c.Y;
a.X = c.X;

在我的代码中,'b'实际上不再可访问,因为它被绑定到某个UI,'a'是我更新'b'的唯一方法。因此,在调用'a = c'之后,b应该具有[1,1]的位置。

3 个答案:

答案 0 :(得分:1)

你可以这样做:

class Wrapper
{
    public Wrapper(Location l)
    {
        this.L = l;
    }
    public Location L;
}

Wrapper a = new Wrapper(new Location(2,1));
Wrapper b = a;
Location c = new Location(1,1);
a.L = c;

如果没有更多的背景,我不确定它是否真的合适。只需添加一个间接级别。

答案 1 :(得分:0)

实验:请随意“将其从水中吹出来”:)在VS 2010 beta 2中针对FrameWork 4.0和3.5(完整版,而不是“客户端”版本)进行测试。

private class indirectReference
{
    // using internal so Loc is not visible outside the class
    internal struct Loc
    {
        public double X;
        public double Y;
    }

    // publicly exposed access to the internal struct
    public Loc pairODoubles;

    // ctor
    public indirectReference(double x, double y)
    {
        pairODoubles.X = x;
        pairODoubles.Y = y;
    }
}

// test ...

indirectReference r1 = new indirectReference(33, 33);

indirectReference r2 = r1;

indirectReference r3 = new indirectReference(66, 66);

// in this case the doubles in r2 are updated 
r1.pairODoubles = r3.pairODoubles;

答案 2 :(得分:0)

您认为MyClass immutable是否合适?

或者:你应该通过包装器执行一些引用计数。