2016-09-23 132 views
0

我試圖重構copy方法copy2這樣的:重構MemberwiseClone使用構造函數

class A 
{ 
    public readonly int x = 42; 
    public int y; 
    public A(int y) 
    { 
     this.y = y; 
    } 
    public A copy(int y) 
    { 
     var c = (A)MemberwiseClone(); 
     c.y = y; 
     return c; 
    } 
    public A copy2(int y) 
    { 
     return new A(y); 
    } 
} 

(因爲這段代碼的真正版本中那樣覆蓋關於MemberwiseClone後場的一半),並與意圖能夠使y只讀。這工作正常A s。但我們也有:

class B : A 
{ 
    public B(int y) : base(y) 
    { 
    } 
} 

MemberwiseClone正確地保存了它的拷貝東西的類型,但我copy2創建每次新A。假設B另有效果只是A的別名,那麼創建正確類型的最佳方法是什麼?

回答

0

我目前的實際的答案是離開代碼是MemberwiseClone然後重挫的什麼抄一半,但我來了這麼遠的解決方案使copyvirtualoverrideB

class A 
{ 
    public readonly int x = 42; 
    public readonly int y; 
    public A(int y) 
    { 
     this.y = y; 
    } 
    public virtual A copy(int y) 
    { 
     return new A(y); 
    } 
} 
class B : A 
{ 
    public B(int y) : base(y) 
    { 
    } 
    public override A copy(int y) 
    { 
     return new B(y); 
    } 
}