关于C#里“浅表副本”的解释

在使用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();
    }
}
原文地址:https://www.cnblogs.com/netlyf/p/1623047.html