深拷贝的实现

来源:互联网 发布:杨众国 知乎 编辑:程序博客网 时间:2024/05/01 00:15
//深拷贝的实现
//2004.9.2
using System;
using System.Collections;
class RefType {
 public String name;
 public Int32 age;
 public RefType(String name,Int32 age)
 {
  this.name = name;
  this.age = age;
 }
}
//类型MyType实现了ICloneable接口,可以被深拷贝
class MyType : ICloneable {
 public RefType r; //引用类型字段
 public String name; //值类型字段
 public Int32 age; //值类型字段
 private ArrayList al = new ArrayList();
 public MyType(String name,Int32 age) {
  this.name = name;
  this.age = age;
  r = new RefType(name,age);
  this.al.Add(this.name);
  this.al.Add(this.age);
  this.al.Add(this.r);
 }
 public object Clone()
 {
  MyType c = new MyType(this.name,this.age);
  c.al = new ArrayList();
  c.al.Add(this.name);
  c.al.Add(this.age);
  c.al.Add(this.r);
  return c;
 }
 public MyType DeepClone(){
  return (MyType)this.Clone();
 }
}
//启动类
class App {
 static void Main() {
   MyType m1 = new MyType("张三",18); //源对象m1
   MyType m2 = (MyType)m1.DeepClone(); //目标对象m2由m1克隆(深拷贝)而来
   Console.WriteLine(m2.name.ToString()+","+m2.age.ToString());
   Console.WriteLine(m2.r.name.ToString()+","+m2.r.age.ToString());
   m1.name = "李四";
   m1.age = 19;
   m1.r.name = "李四";
   m1.r.age = 19;
   Console.WriteLine(m2.name.ToString()+","+m2.age.ToString()); //值类型字段值没有改变
   Console.WriteLine(m2.r.name.ToString()+","+m2.r.age.ToString()); //引用类型字段值也没有改变
 }
}
原创粉丝点击