开发者

How Cloneable to all field [duplicate]

This question already has answers here: Closed 11 y开发者_如何学运维ears ago.

Possible Duplicate:

Deep copy of 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();
    }
}

example:

MyClass m  = new MyClass();
MyClass t = (MyClass)m.Clone();
m.List.Add("qweqeqw");
//m.List.Count == 5
t.ToString();
//t.List.Count==5

but I need a full copy of how to do this?


You need to distinguish between deep copy and shallow copy.

The appropriate way to deep copy is:

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;
}

Where the ICloneable usually used for a shallow copy like:

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.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜