Can somebody please help me to write a DeepCopy routine for this matrix class I have ? I dont have a great deal of experience in C#.
public class Matrix<T>
{
private readonly T[][] _matrix;
private readonly int row;
private readonly in开发者_如何学Ct col;
public Matrix(int x, int y)
{
_matrix = new T[x][];
row = x;
col = y;
for (int r = 0; r < x; r++)
{
_matrix[r] = new T[y];
}
}
}
Thanks in advance
The simplest way of deep copying would be using some kind of serializer (for instance BinaryFormatter
), but this requires not only your type to be decorated as Serializable
, but also the type T.
An example implementation of that could be:
[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);
}
}
}
The issue here, is that you have no control over which type is supplied as generic type parameter. Without knowing more about which kind of types you wish to clone, an option might be to put a generic type constraint on T to only accept types that implement ICloneable
.
In which case you could clone Matrix<T>
like so:
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;
}
}
精彩评论