Deep serialization: the entire state of the serialized object
Use namespace:
Using system. IO;
Using system. runtime. serialization;
Using system. runtime. serialization. formatters. Binary;
Using system. runtime. serialization. formatters. Soap;
Serializable class flag: add the [serializable] feature before the class
Two formats: binaryformatter and soapformatter
Take binaryformatter as an example (soapformatter is the same)
Serialized template:
Public void serializeit (string filename)
{
Book mybook = New Book ();
Binaryformatter formatter = new binaryformatter ();
Filestream FS = file. Create (filename );
Formatter. serialize (FS, mybook );
FS. Close ();
}
Deserialization template:
Public void deserializeit (string filename)
{
Binaryformatter formatter = new binaryformatter ();
Filestream FS = file. openread (filename );
Book mybook = (book) formatter. deserialize (FS );
FS. Close ();
}
* Adding [nonserialized] to a field does not serialize this field.
* If B is referenced in a, [serializable] must be added to a and B to serialize.
* For cyclic references, only circular references of object graphs are supported, and circular references of objects in a broad sense are not supported.
Example of circular object graph reference:
[Serializable]
Public class Book
{
Private bookcatalog includeinbookcatalog;
Public bookcatalog includeinbookcatalog
{
Get {return includeinbookcatalog ;}
Set {includeinbookcatalog = value ;}
}
}
[Serializable]
Public class bookcatalog
{
Private book [] books;
Public book [] books
{
Get {return books ;}
Set
{
Books = value;
Foreach (book in books)
{
Book. includeinbookcatalog = this;
}
}
}
}
In-depth serialization of bookcatalog does not cause circular references, because formatter knows that no matter how many references an object has, each object must be serialized Once-Through system. runtime. implement two classes in serialization: objectmanager and objectidgenerator.
Objectmanager is responsible for tracking objects when objects are deserialized and determining whether the objects have been serialized.
Objectidgenerator adds a unique ID for each tracked object to differentiate whether the object is serialized. objectidgenerator knows whether to return an existing ID or generate a new ID.
The formatter does not check in advance that all objects can be serialized. If an exception occurs in the middle, some objects can be generated.
Object cloning through deep serialization:
First serialize, use binary deep replication on the memory stream; then find the beginning of the stream and perform deserialization
Public object clone (Object source)
{
Memorystream stream = new memorystream ();
Binaryformatter formatter = new binaryformatter ();
Formatter. Context = new streamingcontext (streamingcontextstates. Clone );
Formatter. serialize (stream, source );
Stream. Position = 0;
Return formatter. deserialize (Stream );
}