關於C#裡“淺表副本”的解釋

來源:互聯網
上載者:User

在使用Object類的受保護方法MemberwiseClone ()時,MSDN上的解釋是--建立當前 Object 的淺表副本。那麼什麼是“淺表副本”呢?經過查閱相關資料,得到的解釋是這樣的:

A shallow copy of a collection copies only the elements of the collection, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new collection point to the same objects that the references in the original collection point to. In contrast, a deep copy of a collection copies the elements and everything directly or indirectly referenced by the elements.

一個集合的淺度拷貝意味著只拷貝集合中的元素,不管他們是參考型別或者是實值型別,但是它不拷貝引用所指的對象。這就是說新集合中的引用和原創組合中的引用所指的對象是同一個對象。與此形成對比的是,深度拷貝不僅拷貝集合中的元素,而且還拷貝了這些元素直接或者間接引用的所有東東。這也就意味著,新集合中的引用和原創組合中的引用所指的對象是不同的。

 

關於MemberwiseClone 方法,MSDN上的備忘資訊是這樣的:

MemberwiseClone 方法建立一個淺表副本,方法是建立一個新對象,然後將當前對象的非靜態欄位複製到該新對象。如果欄位是實值型別的,則對該欄位執行逐位複製。如果欄位是參考型別,則複製引用但不複製引用的對象;因此,原始對象及其複本引用同一對象。

例如,考慮一個名為 X 的對象,該對象引用對象 A 和 B。對象 B 又引用對象 C。X 的淺表複本建立一個新對象 X2,該對象也引用對象 A 和 B。與此相對照,X 的深層複本建立一個新對象 X2,該對象引用新對象 A2 和 B2,它們分別是 A 和 B 的副本。B2 又引用新對象 C2,C2 是 C 的副本。使用實現 ICloneable 介面的類執行對象的淺表或深層複製。

還給出了一段代碼作為樣本:

代碼

using System;

class MyBaseClass 
{
    public static string CompanyName = "My Company";
    public int age;
    public string name;
}

class MyDerivedClass: MyBaseClass 
{
    static void Main() 
    {   
          // Creates an instance of MyDerivedClass and assign values to its fields.
          MyDerivedClass m1 = new MyDerivedClass();
          m1.age = 42;
          m1.name = "Sam";
          // Performs a shallow copy of m1 and assign it to m2.
          MyDerivedClass m2 = (MyDerivedClass) m1.MemberwiseClone();
    }
}

 

 

相關文章

聯繫我們

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