【问题标题】:How Cloneable to all field [duplicate]如何克隆到所有字段[重复]
【发布时间】:2011-07-19 01:08:46
【问题描述】:

可能重复:
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();
    }
}

示例:

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

但我需要一份完整的副本?

【问题讨论】:

标签: c# c#-2.0 clone icloneable


【解决方案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.
}

【讨论】:

  • 如果 MyClass 是可继承的,则指示的 DeepCopy 方法将不起作用。正确的克隆方法是有一个受保护的虚拟方法,它调用基类型的克隆方法(如果基类型是 Object,则为 MemberwiseClone);如果要将克隆作为公共接口公开,则非虚拟公共克隆方法应调用私有虚拟方法。
  • @supercat:是的,你说得对,我只是想给他演示一下深拷贝和浅拷贝有什么区别,以及如何初始化它们……
猜你喜欢
  • 2012-10-09
  • 2015-07-13
  • 1970-01-01
  • 1970-01-01
  • 2015-10-09
  • 2012-08-25
  • 2021-06-23
  • 2014-11-15
  • 1970-01-01
相关资源
最近更新 更多