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