在使用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();
}
}