C # Introduction to object cloning)

Source: Internet
Author: User

Shortest copy and deep copy

There are two methods to clone an object: shallow copy and deep copy. A shallow copy is just a copy reference and does not copy the referenced object. A deep COPY Copies the referenced object.

Therefore, the reference in the original object and the same reference in the shallow copy object both point to the same object. A deeply Copied object contains all direct or indirect references to the object. SeeWikipedia(Http://en.wikipedia.org/wiki/Object_copy) To get more explanations.

Icloneable Interface

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

 
Public InterfaceIcloneable
{
ObjectClone ();
}

The problem with icloneable is that the clone method does not explicitly specify whether to execute a shortest copy or a deep copy, so the caller cannot determine the actual situation. Therefore, there are some discussions about removing icloneable from the. NET Framework. The msdn document seems to imply that the clone method is a deep copy, but the document does not explicitly describe:

The icloneable Interface contains a member method, clone, which is intended to support Features beyond memberwiseclone... memberwiseclone is used for shallow copy...

Type-safe clone

Another disadvantage of icloneable is that the clone method returns an object. Therefore, a forced type conversion is required for each clone call.

 
Person Joe= NewPerson ();
Joe. Name= "Joe Smith";
Person joeclone=(Person) Joe. Clone ();

One way to avoid forced type conversion is to provide your own type-safe clone method. Note that you still need to provide the icloneable. Clone method to meet the requirements of the icloneable interface.

Public ClassPerson: icloneable
{
Public StringName;
ObjectIcloneable. Clone ()
{
Return This. Clone ();
}
PublicPerson clone ()
{
Return(Person)This. Memberwiseclone ();
}
}

Select clone method

1. Manually clone

One way to ensure that the object is completely cloned as you think is to manually clone each field of the object ). The disadvantage of this method is that it is troublesome and error-prone: if you add a domain to the class, you may forget to update the clone method. When cloning a reference object and pointing it to the original object, avoid infinite loop references. The following is a simple example of 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. Use the memberwiseclone Method

Memberwiseclone is a protected method of the object class. By creating a new object and copying all the non-static fields of the current object to the new object, you can create a shallow copy. For fields of the value type, the bitwise copy operation is performed. For fields of the reference type, the reference will be assigned a value, but the referenced object will not. Therefore, both the original object and its clone will reference the same object. Note that this method is effective for the derived class, that is, you only need to define the clone method once in the base class. The following is a simple example:

Public ClassPerson: icloneable
{
Public StringName;
PublicPerson spouse;
Public ObjectClone ()
{
Return This. Memberwiseclone ();
}
}

3. Clone Using Reflection

Cloning with reflection creates a new object of the same type using the activator. createinstance method, and then copies all fields with reflection. The advantage of this method is that it is fully automatic and does not need to modify the clone method when adding or deleting members to an object. In addition, it can also be written as a method to provide deep copy. The disadvantage is that reflection is used, so it is slow and unavailable in a trusted environment. ExampleCode

4. Clone using serialization

The simplest way to clone an object is to serialize it and immediately deserialize it into a new object. Like the reflection method, the serialization method is automatic and does not need to be modified when adding or deleting object members. The disadvantage is that serialization is slower than other methods, or even slower than reflection. All referenced objects must be serializable ). In addition, depending on the serialization type (XML, SOAP, binary) you are using, Private Members may not be cloned as expected. The sample code is here, here and here.

5. Clone using IL

A rare solution is to use il (intermediate language) for object cloning. In this way, create a dynamic method, obtain the intermediate language generator (ilgenerator), inject code into the method, compile it into a delegate, and then execute this delegate. The delegate will be cached. Therefore, the intermediate language is generated only during the first clone, and subsequent clones will not be regenerated. Although this method is faster than reflection, it is hard to understand and maintain. Sample Code

6. Clone using extension methods

Havard stranden uses the extention method to create a custom clone framework. This framework can create deep copies of objects and their referenced objects, regardless of the complexity of the object structure. The disadvantage is that this is not providedSource code(Updated: the source code is already included. For more information, see the comments in this article), and it cannot copy objects created by private methods without the parameter-free constructor. Another problem is also shared by all automated deep cloning methods: Deep copy usually requires flexibility to handle special situations that cannot be simply automated (such as unmanaged resources ).

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.