1

可能重复:
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

但我需要一份完整的副本如何做到这一点?

4

1 回答 1

1

你需要区分深拷贝浅拷贝

深度复制的适当方法是:

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.
}
于 2011-07-19T01:33:24.063 回答