深拷貝的實現
來源:互聯網
上載者:User
//深拷貝的實現
//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()); //參考型別欄位值也沒有改變
}
}