用到一个类 A ,但是A没有继承接口 ICloneable ,无法使用 clone 方法对类的对象进行深度复制
请高手帮忙,在这种情况下如何实现深度复制

解决方案 »

  1.   

    似乎只能自己去写一个类似Clone()的方法来实现深度复制了
    比如你有一个类public class A
    {
        public int Elem1;
        public string Elem2;
        public float[] Elem3;
    }现在自己在类中加一个Clone()方法:public class A
    {
        public int Elem1;
        public string Elem2;
        public float[] Elem3;    public A Clone()
        {
            A cloned = new A();
            cloned.Elem1 = this.Elem1;
            cloned.Elem2 = this.Elem2;
            cloned.Elem3 = new float[this.Elem3.Length];
            this.Elem3.CopyTo(cloned.Elem3, 0);
        }
    }类似这样的方法,可以根据你的需要对不同的对象写不周的复制方法,保证可以准确进行深度复制
      

  2.   

    使用拷贝构造函数实现深度复制,大学里的课程public class A
    {
     private Type1 var1;
     public A()
     {
     }
     public A(Type1 var1):this()
     {
        this.var1 =var1;
     }
     public A( A obj):this()
     {
       this.var1 = obj.var1;
     }
    }A A1 = new A(...);
    A A2 = new A(A1);//深度 复制A1到A2
      

  3.   

    BinaryFormatter
    Serialize
    Deserialize