最简单的深度复制方法是使用某种序列化程序(例如BinaryFormatter
),但这不仅需要将您的类型装饰为Serializable
,而且还需要类型 T。
一个示例实现可能是:
[Serializable]
public class Matrix<T>
{
// ...
}
public static class Helper
{
public static T DeepCopy<T>(T obj)
{
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
stream.Position = 0;
return (T) formatter.Deserialize(stream);
}
}
}
这里的问题是,您无法控制作为泛型类型参数提供的类型。在不了解您希望克隆哪种类型的更多信息的情况下,一个选项可能是对 T 施加泛型类型约束以仅接受实现ICloneable
.
在这种情况下,您可以像这样克隆Matrix<T>
:
public class Matrix<T> where T: ICloneable
{
// ... fields and ctor
public Matrix<T> DeepCopy()
{
var cloned = new Matrix<T>(row, col);
for (int x = 0; x < row; x++) {
for (int y = 0; y < col; y++) {
cloned._matrix[x][y] = (T)_matrix[x][y].Clone();
}
}
return cloned;
}
}