讀書釋疑–C#淺拷貝與深拷貝

來源:互聯網
上載者:User

讀書釋疑--C#淺拷貝與深拷貝:
MemberwiseClone 方法建立一個淺表副本,方法是建立一個新對象,然後將當前對象的非靜態欄位複製到該新對象。如果欄位是實值型別的,則對該欄位執行逐位複製。如果欄位是參考型別,則複製引用但不複製引用的對象;因此,原始對象及其複本引用同一對象。
深拷貝,即實現ICloneable介面.ICloneable可用於深拷貝和淺拷貝
請看下面理解那句話.

using System;
using System.Collections.Generic;

public class MyClass
{
    class InstanceA:ICloneable
 {
  public int x;
  public InstanceB B;
  public InstanceA(){}
  public InstanceA(int X,InstanceB b)
  {
   this.x=X;
   this.B=b;
  }
  object ICloneable.Clone()
  {
   return this.Clone();
  }
  public InstanceA Clone()
  {
    InstanceA A=this.MemberwiseClone() as InstanceA;
    A.B=this.B.Copy();
   return A;   //深複製
  //  return (InstanceA)this.MemberwiseClone();  //淺複製
   //return new InstanceA(this.x,this.B);     //use this can't get deep copy too..
   
  }
 }
 class InstanceB
 {
  public int y;
  public InstanceB Copy()
  {
    return this.MemberwiseClone() as InstanceB; 
  }
 }
 
 public static void Main()
 {
    InstanceA obj1=new InstanceA();
    obj1.x=1;
    obj1.B=new InstanceB();
    obj1.B.y=2;
    
  InstanceA obj2=obj1.Clone();
  obj2.x=3;
  obj2.B.y=4;
  Console.WriteLine("Obj1.x is:{0} \t obj1.B.y={1}",obj1.x,obj1.B.y);
     Console.WriteLine("Obj2.x is:{0} \t obj2.B.y={1}",obj2.x,obj2.B.y);
  Console.ReadLine();
 }
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.