On. net, everything is an object. One consequence of this arrangement is that when a variable is assigned to another variable, two variables pointing to the same object will be obtained, instead of two different data copies (unless the value type is used instead of the reference type ). Generally, you can obtain a copy of data by calling a special method exposed by the class. In the. NET world, the class should implement the icloneable interface and expose the unique method clone of this interface, so that external calls can know that it can create a copy of the instance of the class. The Framework has multiple objects to implement this interface, including array, arraylist, bitarray, Font, icon, queue, and stack.
Most of the time, implementing the icloneable interface is quite simple. All other classes are inherited from the system. Object Class. The memberwiseclone method defined in this class can help to copy objects without manually copying the attributes of objects:
// Implements icloneable. Clone method.
Public object clone ()
{
// If the object property is of a complex type, it is still a superficial copy.
// If the object property is of a complex type, manual replication is still required.
// Only use memberwiseclone to copy all non-object values.
Return this. memberwiseclone ();
}
However, this method makes us uncomfortable when using it, because only by modifying the source code of the object definition can we clone an object, because the memberwiseclone method is protected, it can be accessed only within the class. Also, in most cases, the memberwiseclone method executes a superficial copy of the object-that is, it creates a copy of the object, however, no copies of any other objects referenced by this object are created. (That is to say, if data members inside an object are referenced, we still need to manually copy them. If the object graph is very complex, how complicated is the work we face, too many .)
Using Object serialization to process complex object graphs can solve the two problems mentioned above at the same time. In fact, you can create a common method to deeply clone any object.
This is a simple method for serializing and cloning objects:
Public static object cloneobject (Object OBJ)
{
// Create a memory stream
Using (system. Io. memorystream MS = new memorystream (1000 ))
{
Object cloneobject;
// Create a serializer (some books are called serializer)
// It is always slow to create a new serializer object.
Binaryformatter BF = new binaryformatter (null, new streamingcontext (streamingcontextstates. Clone ));
// Serialize an object to a stream
BF. serialize (MS, OBJ );
// Point the stream pointer to the first character
Ms. Seek (0, seekorigin. Begin );
// Deserialization to another object (that is, a deep copy of the original object is created)
Cloneobject = BF. deserialize (MS );
// Close the stream
Ms. Close ();
Return cloneobject;
}
}