我在制作对象的深层副本时遇到了麻烦。
我需要制作 Graph 类对象的深层副本。这是我的Graph
班级和使用对象的Edge
班级。Graph
class Graph : ICloneable
{
private List<Edge> edges;
private List<int> vertices;
public Graph()
{
edges = new List<Edge>();
vertices = new List<int>();
}
public List<Edge> Edges
{
get
{
return edges;
}
}
public List<int> Vertices
{
get
{
return vertices;
}
}
}
class Edge
{
public int vertexV;
public int vertexU;
public int weigth;
public Edge(int vertexV, int vertexU, int weigth)
{
this.vertexV = vertexV;
this.vertexU = vertexU;
this.weigth = weigth;
}
}
到目前为止,我已经尝试过:
public Graph Clone() { return new Graph(this); }
object ICloneable.Clone()
{
return Clone();
}
public Graph(Graph other)
{
this.edges = other.edges;
this.vertices = other.vertices;
}
public object Clone()
{
var clone = (Graph)this.MemberwiseClone();
return clone;
}
但它只创建了一个浅拷贝,并不能解决问题。当然,IClonable
上面的所有示例都实现了接口。我尝试在网上查看其他示例,但没有结果。我正在使用foreach
循环添加所有元素edges
,vertices
但该解决方案非常慢。