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

3

我希望能够一次性更新实例,并将其属性设置为新创建对象的属性,但不会破坏实例与其他变量之间的绑定关系。例如:

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]的位置。


有点困惑于您使用“Location here: in WinForms,'Location'是一个属性,而不是一种类型;这是在WPF中(我了解它不使用'Location'关键字)吗?如果是在WPF中,请标记。谢谢。 - BillW
修复了,它可以是任何类型的对象。 - Shawn Mclean
3个回答

0
你可以像这样做:
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;

我不确定在没有更多上下文的情况下是否真的合适。只需添加一个间接层。


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;

0

你不觉得将 MyClass 设为 不可变 类型是一个合适的方法吗?

或者:你可以通过一个包装器执行一些引用计数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接