ディープコピーの最も簡単な方法は、ある種のシリアライザー(たとえば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;
}
}