Basic serialization and deserialization operations and basic deserialization operations
I. Why serialization?
When a program runs, it needs to access and process data. In object-oriented programming, the data is usually stored in objects. When the program is closed or the object is destroyed, the data needs to be saved somewhere so that the object state can be restored when the object is rebuilt in the future.
Saving an object and its state is called Serialization. The simplest and most common case is to save the object and its state in a file;
Deserialization is a serialized reverse operation that restores a file to an object.
Ii. BinaryFormatter for serialization
. Net provides the following interfaces and classes:
IFormatters |
|
|
The two most important methods in IFormatter are Serialize () and Deserialize, which are used for serialization and deserialization respectively. Because they receive Stream base classes, they can be serialized to any Stream class, not limited to file streams. |
|
Formatters |
|
The namespace provides common enumeration, interfaces, and classes used by the serialized formatter. From |
|
|
Binary |
Used to convert serialized objects to binary data |
|
|
Soap |
Serialize an object to a human-readable text format (reference to this Dll needs to be added ); // This text is described using soap. // SOAP is called simple object access Protocol. It is a lightweight, XML-based Protocol. |
Serialization code:
Note: Serializable is not only required for serialization, but also for attributes and fields of the type.
If a non-serializable attribute is added to the object to be serialized, it should be excluded during serialization. [NonSerialized]
[NonSerialized] can be added only to fields, but not to attributes;
Result:
Iii. BinaryFormatter deserialization
Problem:
// Conn becomes null,
// Because conn is not serialized, the status of the object before serialization is inconsistent with that of the object obtained after deserialization.
// The IDeserializationCallback interface is provided in. NET to complete this task.
To avoid this problem, we use the IDserializationCallBack interface:
Then the interface implementation method is as follows:
After running it again, we will find that conn is no longer null, but an object.
4. Use the SoapFormatter class for serialization
First, compare the similarities and differences with BinaryFormatter
1. The usage is the same;
2. Advantages:
Cross-platform;
Because SOAP is an open protocol, other programs on non-Windows platforms can also process it.
3. Disadvantages:
SOAP is described in XML, so the file size is relatively large.
The result after serialization, as shown in the following figure, is XML: