原创 深拷贝的实现收藏

//深拷贝的实现
//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()); //引用类型字段值也没有改变
 }
}

发表于 @ 2004年09月02日 23:59:00|评论(loading...)

新一篇: 操作符重栽 | 旧一篇: 浅拷贝的实现

用户操作
[即时聊天] [发私信] [加为好友]
Ninth
订阅我的博客
XML聚合  FeedSky
订阅到鲜果
订阅到Google
订阅到抓虾
Ninth的公告
文章分类
收藏
常去的地方
2004级工程硕士校友录
Eleventh的专栏
中国同学录
嘎雅音乐
当秀论坛
我的邮箱
紫丁香BBS
技术类网站
http://blog.csdn.net/cuike519
http://blog.csdn.net/sayo
http://www.jojoo.net
JavaXL
UML软件工程组织
太平洋电脑网
孟岩
源码之家
甲方乙方
计算机世界网
陶清论坛
驱动开发网
与我联系
发E-Mail给我
存档
软件项目交易
Csdn Blog version 3.1a
Copyright © Ninth