C#.net中的浅层和深层克隆

Rag*_*v55 0 c#

class CloneExample : ICloneable
{
    private int m_data ;
    private double m_data2 ;

    public object Clone()
    {
        return this.MemberwiseClone();
    }

    public CloneExample()
    {

    }

    public CloneExample(int data1, int data2)
    {
        m_data = data1;
        m_data2 = data2;
    }

    public override string ToString()
    {
       return String.Format("[d1,d2] {0} {1}", m_data, m_data2);
    }
}
class Program
{
    static void Main(string[] args)
    {
        CloneExample aEx = new CloneExample(10,20);
        CloneExample aEx2 = (CloneExample)aEx.Clone();

        Console.WriteLine("the first object value is {0}", aEx.ToString());
        Console.WriteLine("the first object value is {0}", aEx2.ToString());

        Console.Read();

    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 我写了一个例子来理解浅层克隆是如何工作的.在克隆方法的上面例子中我调用了this.MemberWiseClone(),因为在类中我还没有实现memeberwiseclone.谁将提供默认实现?

cry*_*ted 5

Memberwiseclone首先可能使用Activator.CreateInstance创建实例,然后迭代该类型中的所有字段并将值设置为相应的成员/字段.

但我宁愿根本不使用ICloneable.如果我需要使用克隆,我使用BinaryFormatter序列化对象图,然后反序列化它,以便我得到新的深度克隆实例.

  • 我同意Int3.没有理由实施`ICloneable`..NET Framework的设计者犯了一个错误.见这里:http://blogs.msdn.com/b/brada/archive/2004/05/03/125427.aspx. (3认同)