This topic describes the application of serialization Technology in actual development.
After learning about the object serialization and deserialization methods, we naturally think that we can use them to implement object replication.
When the serialization technology is used for object replication, we will not serialize it to a file, but serialize it To the memory stream. Through deserialization, we can "Bulk clone" a large number of objects.
Example:
Using System;
Using System. Collections. Generic;
Using System. text;
Using System. runtime. serialization. formatters. Binary;
Using System. runtime. serialization;
Using System. IO;
Namespace Objectclone2
{
[Serializable]
Class Myclass
{
Public Int Index = 1 ;
}
Class Program
{
Static Void Main ( String [] ARGs)
{
Myclass OBJ =New Myclass ();
// Create a memory stream object
Using (Memorystream MS = New Memorystream ())
{
Iformatter formator = New Binaryformatter ();
Formator. serialize (MS, OBJ ); // Serialize an object to a memory stream
// Clone 100 objects
For ( Int I = 0 ; I < 100 ; I ++)
{
Ms. Seek ( 0 , Seekorigin. Begin ); // Return to the beginning of the stream
OBJ = (formator. deserialize (MS) As Myclass ); // Deserialization object
OBJ. index + = I; // Set object fields
Console. writeline ( " The object {0} has been created. " , Obj. Index );
}
}
Console. readkey ();
}
}
}
When using the above technology to clone objects, pay attention to the following points:
1. The class to be cloned must be marked as [serializable].
2. The read/write pointer of the memory stream should be moved back to the beginning at the end of each deserialization.
3. For objects with composite relationships, all classes involved in the composite must have the [serializable] Mark.
4. this technique completes object "deep replication", so if there is a circular reference inclusion relationship between objects, the Program may cause stack overflow and throw a stackoverflowexception exception.