Using the serialization and deserialization mechanisms to deeply copy objects)

Source: Internet
Author: User

The value type and reference type have different values. When cloning a member of the reference type of an object, it is generally only a simple assignment to reference the object. In this case, the original object and the new assigned object will reference the same member object at the same time. This method of object clone is generally called shallow assignment or superficial copy. In most cases, the shallow assignment is not the clone method we want.

To achieve deep replication, We must traverse graphs composed of mutually referenced objects and process the cyclic reference structure. This is undoubtedly very complicated. Fortunately, with the serialization and deserialization mechanisms of. net, an object can be cloned in depth. The principle is very simple. First, serialize the object to the memory stream. At this time, the state of the object referenced by the object is saved to the memory .. Net serialization mechanism will automatically handle the situation of loop reference. Then, status information in the memory stream is deserialized into a new object. This completes the deep replication of an object.

Below isCode:

Public   Static   Object Clone ( Object OBJ)
{
If ( ! OBJ. GetType (). isserializable)
{
Throw   New Argumentexception ( " The object is not serializable. " );
}

Iformatter format =   New Binaryformatter ();
Using (Stream stream =   New Memorystream ())
{
Format. serialize (stream, OBJ );
Stream. Seek ( 0 , Seekorigin. Begin );
 
Return Format. deserialize (Stream );
}

}

 

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.