共用方式為


Object.MemberwiseClone 方法

定義

建立目前 Object的淺層複本。

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

傳回

目前 Object的淺層複本。

範例

下列範例說明 MemberwiseClone 方法。 它會定義 ShallowCopy 方法,這個方法會呼叫 MemberwiseClone 方法,以在 Person 對象上執行淺層複製作業。 它也會定義 DeepCopy 方法,在 Person 對象上執行深層複製作業。

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)MemberwiseClone();
    }

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

public class Example
{
    public static void Main()
    {
        // Create an instance of Person and assign values to its fields.
        Person p1 = new()
        {
            Age = 42,
            Name = "Sam",
            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.Age = 39;
        p1.Name = "George";
        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: {p.Name:s}, Age: {p.Age:d}");
        Console.WriteLine($"      Value: {p.IdInfo.IdNumber:d}");
    }
}

/* 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
 */
open System

type IdInfo(IdNumber) =
    member val IdNumber = IdNumber with get, set

type Person() =
    [<DefaultValue>]
    val mutable public Age: int
    [<DefaultValue>]
    val mutable public Name: string
    [<DefaultValue>]
    val mutable public IdInfo: IdInfo

    member this.ShallowCopy() =
        this.MemberwiseClone() :?> Person

    member this.DeepCopy() =
       let other = this.MemberwiseClone() :?> Person
       other.IdInfo <- IdInfo this.IdInfo.IdNumber
       other

let displayValues (p: Person) =
    printfn $"      Name: {p.Name:s}, Age: {p.Age:d}"
    printfn $"      Value: {p.IdInfo.IdNumber:d}"

// Create an instance of Person and assign values to its fields.
let p1 = Person()
p1.Age <- 42
p1.Name <- "Sam"
p1.IdInfo <- IdInfo 6565

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

// Display values of p1, p2
printfn "Original values of p1 and p2:"
printfn "   p1 instance values: "
displayValues p1
printfn "   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
printfn "\nValues of p1 and p2 after changes to p1:"
printfn "   p1 instance values: "
displayValues p1
printfn "   p2 instance values:"
displayValues p2

// Make a deep copy of p1 and assign it to p3.
let p3 = p1.DeepCopy()
// Change the members of the p1 class to new values to show the deep copy.
p1.Age <- 39
p1.Name <- "George"
p1.IdInfo.IdNumber <- 8641
printfn "\nValues of p1 and p3 after changes to p1:"
printfn "   p1 instance values: "
displayValues p1
printfn "   p3 instance values:"
displayValues p3

// 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(MemberwiseClone(), Person)
    End Function

    Public Function DeepCopy() As Person
        Dim other As Person = DirectCast(MemberwiseClone(), Person)
        other.IdInfo = New IdInfo(IdInfo.IdNumber)
        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.Age = 39
        p1.Name = "George"
        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 物件。 如範例輸出所示,當呼叫 MemberwiseClone 方法複製 Person 物件時,複製的 Person 對像是原始對象的獨立複本,不同之處在於它們共用相同的 Person.IdInfo 對象參考。 因此,修改複製的 Person.IdInfo 屬性會變更原始物件的 Person.IdInfo 屬性。 另一方面,執行深層複製作業時,可以修改複製 Person 物件,包括其 Person.IdInfo 屬性,而不會影響原始物件。

備註

MemberwiseClone 方法會建立淺層複本,方法是建立新的 對象,然後將目前物件的非靜態字段複製到新的物件。 如果欄位是實值類型,則會執行欄位的位元組複本。 如果欄位是參考型別,則會複製參考,但參考物件不是;因此,原始物件及其複製品會參考相同的物件。

為了說明淺層和深層複製作業之間的差異,請考慮參考物件 A 和 B 的物件 X。物件 B 接著參考物件 C。X 的淺層複本會建立也參考物件 A 和 B 的新物件 X2。相反地,X 的深層複本會建立新的物件 X2,參考新的物件 A2 和 B2,也就是 A 和 B.B2 的複本,接著會參考 C2 的新物件 C2。

如果 MemberwiseClone 方法執行的淺層複製作業不符合您的需求,則有許多方式可以實作深層複製作業。 這些包括下列各項:

  • 呼叫要複製之 物件的類別建構函式,以建立具有從第一個物件取得之屬性值的第二個物件。 這假設物件的值完全是由其類別建構函式所定義。
  • 呼叫 MemberwiseClone 方法來建立對象的淺層複本,然後將值與原始物件相同的新物件指派給值是參考型別的任何屬性或字段。 範例中的 DeepCopy 方法說明此方法。
  • 將物件串行化為深層複製,然後將串行化的數據還原至不同的物件變數。
  • 使用具有遞歸的反映來執行深層複製作業。

適用於