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 に答える