深拷貝的實現

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.