可能重复:
List的深度复制<T>
public class MyClass : ICloneable
{
private List<string> m_list = new List<string>();
public MyClass()
{
List.Add("1111");
List.Add("2222");
List.Add("3333");
List.Add("4444");
}
public List<string> List
{
get { return m_list; }
set { m_list = value; }
}
public object Clone()
{
return this.MemberwiseClone();
}
}
示例:
MyClass m = new MyClass();
MyClass t = (MyClass)m.Clone();
m.List.Add("qweqeqw");
//m.List.Count == 5
t.ToString();
//t.List.Count==5
但我需要一份如何做到这一点的完整副本?
您需要区分深度复制和浅层复制 深度复制的合适方法是: 其中public MyClass DeepCopy()
{
MyClass copy = new MyClass();
copy.List = new List<string>(m_List);//deep copy each member, new list object is created
return copy;
}
ICloneable
通常用于浅拷贝,如:public object Clone()
{
MyClass copy = new MyClass();
copy.List = List;//notice the difference here. This uses the same reference to the List object, so if this.List.Add it will add also to the copy list.
return copy;
//Note: Also return this.MemberwiseClone(); will do the same effect.
}