1

有人可以帮我为我拥有的这个矩阵类编写一个 DeepCopy 例程吗?我在 C# 方面没有很多经验。

public class Matrix<T>
{
    private readonly T[][] _matrix;
    private readonly int row;
    private readonly int 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];
        }
    }
}

提前致谢

4

1 回答 1

2

最简单的深度复制方法是使用某种序列化程序(例如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;
  }
}
于 2011-10-13T10:58:25.687 回答