.NET Framework Class Library Object..::.MemberwiseClone Method Updated: September 2010 Creates a shallow copy of the current Object.
Namespace:
System
Assembly:
mscorlib (in mscorlib.dll)

Syntax
Protected Function MemberwiseClone As Object
protected Object MemberwiseClone()
protected:
Object^ MemberwiseClone()
member MemberwiseClone : unit -> Object

Remarks
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. 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. 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. 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. 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.

Examples
The following example illustrates the MemberwiseClone method. It defines a ShallowCopy method that calls the MemberwiseClone method to perform a shallow copy operation on a Person object. It also defines a DeepCopy method that performs a deep copy operation on a Person object.
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(Me.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 = DirectCast(p1.ShallowCopy(), Person)
' 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
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(this.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 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 = (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);
// 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
In this example, the Person.IdInfo property returns an IdInfo object. 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. As a result, modifying the clone's Person.IdInfo property changes the original object's Person.IdInfo property. 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.

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileSupported in: 4, 3.5 SP1 Portable Class LibrarySupported in: Portable Class Library

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

See Also

Change History
Date | History | Reason |
|---|
September 2010
| Revised the Remarks section and replaced the example. |
Customer feedback.
|
|
Biblioteca de clases de .NET Framework Object..::.MemberwiseClone (Método) Crea una copia superficial del objeto Object actual.
Espacio de nombres:
System
Ensamblado:
mscorlib (en mscorlib.dll)

Sintaxis
Protected Function MemberwiseClone As Object
protected Object MemberwiseClone()
protected:
Object^ MemberwiseClone()
member MemberwiseClone : unit -> Object

Comentarios
El método MemberwiseClone crea una copia superficial mediante la creación de un nuevo objeto y la copia posterior de los campos no estáticos del objeto actual en el objeto nuevo. Si un campo es de un tipo de valor, se realiza una copia bit a bit de él. Si un campo es de un tipo de referencia, se copia la referencia, pero no el objeto al que se hace referencia; por consiguiente, el objeto original y su copia hacen referencia al mismo objeto. Por ejemplo, considere un objeto denominado X que hace referencia a los objetos A y B. El objeto B, a su vez, hace referencia al objeto C. Una copia superficial de X crea nuevo objeto X2, que también hace referencia a los objetos A y B. En contraste, una copia en profundidad de X crea un nuevo objeto X2 que hace referencia a los nuevos objetos A2 y B2, de los que son las copias A y B. B2, a su vez, hace referencia al nuevo objeto C2, que es una copia C. En el ejemplo se muestra la diferencia entre una operación de copia superficial y de copia en profundidad. Hay numerosas maneras de implementar una operación de la copia en profundidad si la operación de copia superficial realizada por el método MemberwiseClone no satisface sus necesidades. Se incluyen las siguientes: Llame a un constructor de clase del objeto que se va a copiar para crear un segundo objeto con valores de propiedad tomado del primer objeto. Esto supone que los valores de un objeto están completamente definidos por su constructor de clase. Llame al método MemberwiseClone para crear una copia superficial de un objeto y, a continuación, asigne nuevos objetos cuyos valores son igual que el objeto original a las propiedades o campos cuyos valores sean los tipos de referencia. El método DeepCopy del ejemplo ilustra este enfoque. Serialice el objeto del que se va a hacer una copia profunda y, a continuación, restaure los datos serializados a una variable de objeto diferente. Utilice la reflexión con recursividad para realizar la operación de copia en profundidad.

Ejemplos
En el siguiente ejemplo se muestra el método MemberwiseClone. Define un método ShallowCopy que llama al método MemberwiseClone para realizar una operación de copia superficial en un objeto Person. También define un método DeepCopy que realiza una operación de copia en profundidad en un objeto Person.
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(Me.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 = DirectCast(p1.ShallowCopy(), Person)
' 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
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(this.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 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 = (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);
// 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
En este ejemplo, la propiedad Person.IdInfo devuelve un objeto IdInfo. Como muestra el resultado del ejemplo , cuando un objeto Person se clona llamando al método MemberwiseClone, el objeto Person clonado es una copia independiente del objeto original, solo que comparten la misma referencia de objeto Person.IdInfo. Como resultado, al modificar la propiedad Person.IdInfo del clon, se cambia la propiedad Person.IdInfo del objeto original. Por otro lado, cuando se realiza una operación de copia en profundidad, el objeto Person clonado, incluso su propiedad Person.IdInfo, se puede modificar sin afectar al objeto original.

Información de versión
.NET FrameworkCompatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileCompatible con: 4, 3.5 SP1 Compatible con:

Plataformas
Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2
.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

Vea también

Historial de cambios
Fecha | Historial | Motivo |
|---|
Septiembre de 2010
| Revisada la sección Notas y reemplazado el ejemplo. |
Comentarios de los clientes.
|
|