Object.MemberwiseClone 方法

定義

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

protected:
 System::Object ^ MemberwiseClone();
protected object MemberwiseClone ();
member this.MemberwiseClone : unit -> obj
Protected Function MemberwiseClone () As Object

傳回

目前 Object 的淺層複製。A shallow copy of the current Object.

範例

下列範例說明 MemberwiseClone 方法。The following example illustrates the MemberwiseClone method. 它會定義一個 ShallowCopy 方法,以呼叫 MemberwiseClone 方法,在 Person 物件上執行淺層複製作業。It defines a ShallowCopy method that calls the MemberwiseClone method to perform a shallow copy operation on a Person object. 它也會定義在 Person 物件上執行深層複製作業的 DeepCopy 方法。It also defines a DeepCopy method that performs a deep copy operation on a Person object.

using System;

public class IdInfo
{
    public int IdNumber;
    
    public IdInfo(int IdNumber)
    {
        this.IdNumber = IdNumber;
    }
}

public class Person 
{
    public int Age;
    public string Name;
    public IdInfo IdInfo;

    public Person ShallowCopy()
    {
       return (Person) this.MemberwiseClone();
    }

    public Person DeepCopy()
    {
       Person other = (Person) this.MemberwiseClone();
       other.IdInfo = new IdInfo(IdInfo.IdNumber);
       other.Name = String.Copy(Name);
       return other;
    }
}

public class Example
{
    public static void Main()
    {
        // Create an instance of Person and assign values to its fields.
        Person p1 = new Person();
        p1.Age = 42;
        p1.Name = "Sam";
        p1.IdInfo = new IdInfo(6565);

        // Perform a shallow copy of p1 and assign it to p2.
        Person p2 = p1.ShallowCopy();

        // Display values of p1, p2
        Console.WriteLine("Original values of p1 and p2:");
        Console.WriteLine("   p1 instance values: ");
        DisplayValues(p1);
        Console.WriteLine("   p2 instance values:");
        DisplayValues(p2);
        
        // Change the value of p1 properties and display the values of p1 and p2.
        p1.Age = 32;
        p1.Name = "Frank";
        p1.IdInfo.IdNumber = 7878;
        Console.WriteLine("\nValues of p1 and p2 after changes to p1:");
        Console.WriteLine("   p1 instance values: ");
        DisplayValues(p1);
        Console.WriteLine("   p2 instance values:");
        DisplayValues(p2);

        // Make a deep copy of p1 and assign it to p3.
        Person p3 = p1.DeepCopy();
        // Change the members of the p1 class to new values to show the deep copy.
        p1.Name = "George";
        p1.Age = 39;
        p1.IdInfo.IdNumber = 8641;
        Console.WriteLine("\nValues of p1 and p3 after changes to p1:");
        Console.WriteLine("   p1 instance values: ");
        DisplayValues(p1);
        Console.WriteLine("   p3 instance values:");
        DisplayValues(p3);
    }

    public static void DisplayValues(Person p)
    {
        Console.WriteLine("      Name: {0:s}, Age: {1:d}", p.Name, p.Age);
        Console.WriteLine("      Value: {0:d}", p.IdInfo.IdNumber);
    }
}
// The example displays the following output:
//       Original values of p1 and p2:
//          p1 instance values:
//             Name: Sam, Age: 42
//             Value: 6565
//          p2 instance values:
//             Name: Sam, Age: 42
//             Value: 6565
//       
//       Values of p1 and p2 after changes to p1:
//          p1 instance values:
//             Name: Frank, Age: 32
//             Value: 7878
//          p2 instance values:
//             Name: Sam, Age: 42
//             Value: 7878
//       
//       Values of p1 and p3 after changes to p1:
//          p1 instance values:
//             Name: George, Age: 39
//             Value: 8641
//          p3 instance values:
//             Name: Frank, Age: 32
//             Value: 7878
Public Class IdInfo
    Public IdNumber As Integer
    
    Public Sub New(IdNumber As Integer)
        Me.IdNumber = IdNumber
    End Sub
End Class

Public Class Person 
    Public Age As Integer
    Public Name As String
    Public IdInfo As IdInfo

    Public Function ShallowCopy() As Person
       Return DirectCast(Me.MemberwiseClone(), Person)
    End Function

    Public Function DeepCopy() As Person
       Dim other As Person = DirectCast(Me.MemberwiseClone(), Person) 
       other.IdInfo = New IdInfo(IdInfo.IdNumber)
       other.Name = String.Copy(Name)
       Return other
    End Function
End Class

Module Example
   Public Sub Main()
        ' Create an instance of Person and assign values to its fields.
        Dim p1 As New Person()
        p1.Age = 42
        p1.Name = "Sam"
        p1.IdInfo = New IdInfo(6565)

        ' Perform a shallow copy of p1 and assign it to p2.
        Dim p2 As Person = p1.ShallowCopy()

        ' Display values of p1, p2
        Console.WriteLine("Original values of p1 and p2:")
        Console.WriteLine("   p1 instance values: ")
        DisplayValues(p1)
        Console.WriteLine("   p2 instance values:")
        DisplayValues(p2)
        Console.WriteLine()
                
        ' Change the value of p1 properties and display the values of p1 and p2.
        p1.Age = 32
        p1.Name = "Frank"
        p1.IdInfo.IdNumber = 7878
        Console.WriteLine("Values of p1 and p2 after changes to p1:")
        Console.WriteLine("   p1 instance values: ")
        DisplayValues(p1)
        Console.WriteLine("   p2 instance values:")
        DisplayValues(p2)
        Console.WriteLine()
        
        ' Make a deep copy of p1 and assign it to p3.
        Dim p3 As Person = p1.DeepCopy()
        ' Change the members of the p1 class to new values to show the deep copy.
        p1.Name = "George"
        p1.Age = 39
        p1.IdInfo.IdNumber = 8641
        Console.WriteLine("Values of p1 and p3 after changes to p1:")
        Console.WriteLine("   p1 instance values: ")
        DisplayValues(p1)
        Console.WriteLine("   p3 instance values:")
        DisplayValues(p3)
   End Sub
   
    Public Sub DisplayValues(p As Person)
        Console.WriteLine("      Name: {0:s}, Age: {1:d}", p.Name, p.Age)
        Console.WriteLine("      Value: {0:d}", p.IdInfo.IdNumber)
    End Sub
End Module
' The example displays the following output:
'       Original values of m1 and m2:
'          m1 instance values:
'             Name: Sam, Age: 42
'             Value: 6565
'          m2 instance values:
'             Name: Sam, Age: 42
'             Value: 6565
'       
'       Values of m1 and m2 after changes to m1:
'          m1 instance values:
'             Name: Frank, Age: 32
'             Value: 7878
'          m2 instance values:
'             Name: Sam, Age: 42
'             Value: 7878
'       
'       Values of m1 and m3 after changes to m1:
'          m1 instance values:
'             Name: George, Age: 39
'             Value: 8641
'          m3 instance values:
'             Name: Frank, Age: 32
'             Value: 7878

在此範例中,Person.IdInfo 屬性會傳回 IdInfo 物件。In this example, the Person.IdInfo property returns an IdInfo object. 如範例的輸出所示,當 Person 物件是藉由呼叫 MemberwiseClone 方法進行複製時,複製的 Person 物件是原始物件的獨立複本,不同之處在于它們共用相同的 Person.IdInfo 物件參考。As the output from the example shows, when a Person object is cloned by calling the MemberwiseClone method, the cloned Person object is an independent copy of the original object, except that they share the same Person.IdInfo object reference. 因此,修改複製的 Person.IdInfo 屬性會變更原始物件的 Person.IdInfo 屬性。As a result, modifying the clone's Person.IdInfo property changes the original object's Person.IdInfo property. 另一方面,執行深層複製作業時,可以修改複製的 Person 物件,包括其 Person.IdInfo 屬性,而不會影響原始物件。On the other hand, when a deep copy operation is performed, the cloned Person object, including its Person.IdInfo property, can be modified without affecting the original object.

備註

MemberwiseClone 方法會建立新的物件,然後將目前物件的非靜態欄位複製到新的物件,藉以建立淺層複本。The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. 如果欄位是實值型別,則會執列欄位的逐位複製。If a field is a value type, a bit-by-bit copy of the field is performed. 如果欄位是參考型別,則會複製參考,但參照的物件則不會。因此,原始物件和其複製會參考相同的物件。If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.

例如,假設名為 X 的物件參考物件 A 和 B。物件 B 接著會參考物件 C。X 的淺層複本會建立新的物件 X2,同時參考物件 A 和 B。相反地,X 的深層複本會建立新的物件 X2,參考新物件 A2 和 B2,而這是 A 和 B 的複本。然後,B2 會參考新的物件 C2,這是 C 的複本。此範例說明淺層和深層複製作業之間的差異。For example, consider an object called X that references objects A and B. Object B, in turn, references object C. A shallow copy of X creates new object X2 that also references objects A and B. In contrast, a deep copy of X creates a new object X2 that references the new objects A2 and B2, which are copies of A and B. B2, in turn, references the new object C2, which is a copy of C. The example illustrates the difference between a shallow and a deep copy operation.

如果 MemberwiseClone 方法所執行的淺層複製作業不符合您的需求,有許多方式可以執行深層複製作業。There are numerous ways to implement a deep copy operation if the shallow copy operation performed by the MemberwiseClone method does not meet your needs. 包含以下各項:These include the following:

  • 呼叫要複製之物件的類別處理函式,以建立第二個物件,其中具有取自第一個物件的屬性值。Call a class constructor of the object to be copied to create a second object with property values taken from the first object. 這會假設物件的值完全是由其類別的函式所定義。This assumes that the values of an object are entirely defined by its class constructor.

  • 呼叫 MemberwiseClone 方法來建立物件的淺層複本,然後將其值與原始物件相同的新物件,指派給其值為參考型別的任何屬性或欄位。Call the MemberwiseClone method to create a shallow copy of an object, and then assign new objects whose values are the same as the original object to any properties or fields whose values are reference types. 範例中的 DeepCopy 方法會說明這種方法。The DeepCopy method in the example illustrates this approach.

  • 將要深層複製的物件序列化,然後將序列化的資料還原到不同的物件變數。Serialize the object to be deep copied, and then restore the serialized data to a different object variable.

  • 使用反映搭配遞迴來執行深層複製作業。Use reflection with recursion to perform the deep copy operation.

適用於