当自定义类的成员是值类型的时候,深浅拷贝无差异(string类型由于不可修改的特性,也无差异)。
当成员是引用类型的时候,浅拷贝的定义是:拷贝的副本,引用类型成员只拷贝了成员地址,修改副本的引用类型成员,主本也被修改了,深拷贝的定义是,对于引用类型成员,重新创建实例,主副本修改,互不影响。代码实例:
[Serializable] public Employee:ICloneable { public string IDCode{set;get;} public int Age{set;get;} public Department department{set;get;} public object Clone() { return this.MemberwiseClone(); } public Employee DeepClone() { using(Stream objectStream=new MemoryStream()) { IFormatter formatter=new BinaryFormatter(); formatter.Serialize(objectStream,this); objectStream.Seek(0,SeekOrigin.Begin); return formatter.Deserialize(objectStream) as Emloyee; } } public Employee ShallowClone() { return Clone() as Employee; } }