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
的別名,那麼創建正確類型的最佳方法是什麼?