2010-01-16 63 views
3

我想一次更新一個具有新創建對象的屬性的實例,但不會將實例綁定到其他變量。例如。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,「一」是我通過更新「B」唯一的辦法。所以在調用'a = c'之後,b應該有[1,1]的位置。

+0

有點困惑你'使用位置:在WinForms中'位置是一個屬性,而不是一個類型;這是在WPF(我明白不使用'位置關鍵字)?如果在WPF中,請標記。謝謝, – BillW 2010-01-16 08:18:54

+0

固定它,它可以是任何類型的對象。 – 2010-01-16 08:25:01

回答

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; 
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; 

我不知道它是否是沒有更多的背景真是再合適不過了。只需添加一個間接級別即可。

0

你不覺得製作MyClassimmutable將是一個合適的方法?

或者:您應該通過包裝執行一些引用計數。