我有一个Tile
使用这种方法的课程:
public object Clone()
{
return MemberwiseClone();
}
另一个Checker
继承自Tile
.
我也有一Board
堂课是List<Tile>
. 我想克隆板,所以我写了这个:
public Board Clone()
{
var b = new Board(width, height);
foreach (var t in this) b.Add(t.Clone());
return b;
}
但它会抛出一个错误:
无法从“对象”转换为“Checkers.Tile”
现在我可以让该Tile.Clone
方法返回 a Tile
,但是是否也会MemberwiseClone
复制 sub- 中的附加属性Checker
?
Board.Clone
如果这不是问题,那么上述方法与此之间的语义区别是什么?
public Board Clone()
{
using (var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, this);
ms.Position = 0;
return (Board)bf.Deserialize(ms);
}
}
因为它们肯定对我的程序有不同的影响,即使当我打印板时它看起来是一样的。我不认为正在克隆某些东西,但正在返回引用。Board
ctor 看起来像这样:
public Board(int width = 8, int height = 8)
{
this.width = width;
this.height = height;
this.rowWidth = width / 2;
this.Capacity = rowWidth * height;
}
该类Tile
实际上没有任何属性。检查器只有两个枚举属性:
public enum Color { Black, White };
public enum Class { Man, King };
public class Checker : Tile
{
public Color Color { get; set; }
public Class Class { get; set; }