当前位置:编程学习 > C#/ASP.NET >>

关于深度复制自定义对象属性,字段的拷贝,急

关于深度复制自定义对象属性,字段的拷贝,急

如上述

--------------------编程问答-------------------- C#:浅谈对象数组,运算符重载和深度复制的应用 

http://blog.csdn.net/smartken0824/archive/2007/07/08/1683053.aspx --------------------编程问答-------------------- up --------------------编程问答-------------------- try 反射
--------------------编程问答--------------------
using System;
using System.Collections.Generic;

public class MyClass
{
    class InstanceA:ICloneable
 {
  public int x;
  public InstanceB B;
  public InstanceA(){}
  public InstanceA(int X,InstanceB b)
  {
   this.x=X;
   this.B=b;
  }
  object ICloneable.Clone()
  {
   return this.Clone();
  }
  public InstanceA Clone()
  {
    InstanceA A=this.MemberwiseClone() as InstanceA;
    A.B=this.B.Copy();
   return A;   //深复制
  //  return (InstanceA)this.MemberwiseClone();  //浅复制
   //return new InstanceA(this.x,this.B);     //use this can't get deep copy too..
   
  }
 }
 class InstanceB
 {
  public int y;
  public InstanceB Copy()
  {
    return this.MemberwiseClone() as InstanceB; 
  }
 }
 
 public static void Main()
 {
    InstanceA obj1=new InstanceA();
    obj1.x=1;
    obj1.B=new InstanceB();
    obj1.B.y=2;
    
  InstanceA obj2=obj1.Clone();
  obj2.x=3;
  obj2.B.y=4;
  Console.WriteLine("Obj1.x is:{0} \t obj1.B.y={1}",obj1.x,obj1.B.y);
     Console.WriteLine("Obj2.x is:{0} \t obj2.B.y={1}",obj2.x,obj2.B.y);
  Console.ReadLine();
 }
}

浅拷贝是指当对象的字段值被拷贝时,字段引用的对象不会被拷贝,这样,当拷贝完毕后,源对象和拷贝对象的字段会引用同一个值。  
深拷贝是对对象实例中字段引用的对象也进行拷贝的一种方式,这样,新对象将引用新的字符串。需要注意的是,执行深拷贝后,源对象和拷贝对象不会共享任何东西,改变一个对象对另一个对象没有任何影响。
http://topic.csdn.net/u/20080211/17/323a5b2f-2cab-4463-96bd-2a86fe5921d1.html
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,