C# DeepCopy 例程
有人可以帮我为我拥有的这个矩阵类编写 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];
}
}
}
提前致谢
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 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];
}
}
}
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
深度复制的最简单方法是使用某种序列化程序(例如
BinaryFormatter
),但这不仅需要你的类型被修饰为可序列化
,也是 T 类型。其实现示例如下:
这里的问题是您无法控制作为泛型类型参数提供的类型。如果不知道更多关于您希望克隆哪种类型的信息,一个选项可能是对 T 施加通用类型约束,以仅接受实现
ICloneable
。在这种情况下,您可以像这样克隆
Matrix
: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 asSerializable
, but also the type T.An example implementation of that could be:
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: