我有一个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;
}
但它会抛出一个错误:
无法从“object”转换为“Checkers.Tile”
现在我可以做Tile.Clone
方法返回一个Tile
相反,但随后将MemberwiseClone
复制子中的附加属性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);
}
}
因为它们肯定会对我的程序产生不同的影响,即使当我打印电路板时looks相同。我不认为有什么事情正在发生cloned但正在返回一个引用。这Board
演员看起来像这样:
public Board(int width = 8, int height = 8)
{
this.width = width;
this.height = height;
this.rowWidth = width / 2;
this.Capacity = rowWidth * height;
}
The 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; }