开发者

C# Update Object Properties without breaking instance

I want to update an instance with properties of a newly created object at once but not breaking the instance binding to other variables. For eg.

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;

In my code, 'b' is actua开发者_Go百科lly not accessible anymore because it is binded to some UI, 'a' is my only way through updating 'b'. So after 'a = c' is called, b should have the location of [1,1].


Experimental : please feel free to "blow this out of the water" :) Tested in VS 2010 beta 2 against FrameWork 4.0 and 3.5 (full, not "client" versions).

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;


You could do something like this:

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;

I'm not sure whether it's really appropriate without more context. Just add a level of indirection.


Don't you think making the MyClass immutable would be a suitable approach?

Or: you should perform some reference counting, through a wrapper.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜