Introduction to C # object cloning

Source: Internet
Author: User

Shallow copy and deep copy

There are two methods of object cloning: Shallow copy and deep copy. A shallow copy simply copies the reference and does not copy the referenced object. A deep copy copies the referenced object.

Therefore, both the reference in the original object and the same reference in the shallow copy object point to the same object. Deep-copy objects contain all direct or indirect references to objects. See Wikipedia (http://en.wikipedia.org/wiki/Object_copy) for more explanations.

ICloneable interface

The ICloneable interface contains a clone method that can be used to create a copy of the current object.

public interface ICloneable
{
Object Clone ();
}


The problem with ICloneable is that the Clone method does not explicitly specify that a shallow copy or deep copy is performed, so the caller will not be able to determine the actual situation. Therefore, there is some discussion about the elimination of icloneable from the. NET Framework. The MSDN documentation seems to imply that the Clone method is a deep copy, but the document does not have a clear description:

The ICloneable interface contains a member method, Clone, which is intended to support more than the functionality provided by memberwiseclone ... MemberwiseClone is a shallow copy ...

Type-safe cloning

Another disadvantage of ICloneable is that the Clone method returns an object, so that each call to clone will be forced to cast the type one at a time.

Person Joe = new Person ();
Joe. Name = "Joe Smith";
Person Joeclone = (person) Joe. Clone ();


One way to avoid forcing type conversions is to provide your own type-safe Clone method. Note that you still have to provide the ICloneable.Clone method to meet the requirements of the ICloneable interface.

public class Person:icloneable
{
public string Name;
Object ICloneable.Clone ()
{
return this. Clone ();
}
Public Person Clone ()
{
return (person). MemberwiseClone ();
}
}

Choose a Cloning method

1. Manual Cloning

A way to make sure that the object is cloned exactly as you want to, is to manually clone each field of the object (field). The disadvantage of this approach is trouble and error-prone: If you add a field to your class, you'll probably forget to update the Clone method. Also, be careful to avoid infinite circular references when cloning a reference object to the original object. Here is a simple example of a deep copy:

public class Person:icloneable
{
public string Name;
public person spouse;
public Object Clone ()
{
Person p = new person ();
P.name = this. Name;
if (this. spouse = null)
P.spouse = (person) this. Spouse.clone ();
return p;
}
}

2. Using the MemberwiseClone method

MemberwiseClone is a protected method of the object class that creates a shallow copy by creating a new object and copying non-static fields from all current objects into the new object. For a field of value type, a bitwise copy is made. For a field of a reference type, the reference will be assigned a value and the object referenced is not. As a result, both the original object and its clone reference the same object. Note that this method is valid for derived classes, meaning that you only have to define the Clone method once in the base class. The following is a simple example:

public class Person:icloneable
{
public string Name;
public person spouse;
public Object Clone ()
{
return this. MemberwiseClone ();
}
}

3. Cloning with Reflection

Cloning with reflection uses the Activator.CreateInstance method to create a new object of the same type, and then uses reflection to make a shallow copy of all the fields. The advantage of this approach is that it is fully automatic and does not need to modify the Clone method when adding or removing members from the object. It can also be written as a way to provide deep copies. The disadvantage is that reflection is used, so it is slower and is not available in a partially trusted environment. Sample code

4. Cloning using serialization

The simplest way to clone an object is to serialize it and immediately deserialize it into a new object. As with the reflection method, the serialization method is automatic and does not need to be modified when adding or deleting an object member. The disadvantage is that serialization is slower than other methods, and even slower than reflection, all referenced objects must be serializable (Serializable). Also, depending on the type of serialization you are using (Xml,soap, binary), private members may not be cloned as expected. The sample code is here, here and here.

5. Cloning using IL

A rare solution is to use IL (intermediate language) for object cloning. This method creates a dynamic method (DynamicMethod), gets the intermediate language generator (ILGenerator), injects code into the method, compiles it into a delegate, and executes the delegate. The delegate is cached, so the intermediate language is generated only at the time of the initial clone, and subsequent clones are not regenerated again. Although this method is faster than using reflection, this approach is difficult to understand and maintain. Sample code

6. Cloning using the extension method

Havard Stranden creates a custom clone frame with the extension method (extention). This framework enables you to create deep copies of objects and the objects they reference, regardless of how complex the object structure is. The downside is that this is a custom framework that does not provide source code (update: The source code is now included, see the comments in this article), and it cannot copy objects created by private methods when no parameterless constructor is used. Another problem, also common to all automated deep cloning methods, is that deep copies often require flexibility to handle special situations that cannot be easily automated (for example, non-managed resources).

Http://www.cnblogs.com/gengaixue/archive/2012/07/11/2586411.html

Introduction to C # object cloning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.