CHAPTER 20 FILE I/O AND OBJECT SERIALIZATION
[OnDeserializing]
This attribute allows you to specify a method that will be called before
the deserialization process.
[OnSerialized]
This attribute allows you to specify a method that will be called
immediately after the object has been serialized.
[OnSerializing]
This attribute allows you to specify a method that will be called before
the serialization process.
[OptionalField]
This attribute allows you to define a field on a type that can be missing
from the specified stream.
[SerializationInfo]
In essence, this class is a property bag that maintains name/value pairs
representing the state of an object during the serialization process.
A Deeper Look at Object Serialization
Before you examine various ways that you can customize the serialization process, you will find it
helpful to take a deeper look at what takes place behind the scenes. When the BinaryFormatter serializes
an object graph, it is in charge of transmitting the following information into the specified stream:
•
The fully qualified name of the objects in the graph (e.g., MyApp.JamesBondCar)
•
The name of the assembly defining the object graph (e.g., MyApp.exe)
•
An instance of the SerializationInfo class that contains all stateful data
maintained by the members in the object graph
During the deserialization process, the BinaryFormatter uses this same information to build an
identical copy of the object, using the information extracted from the underlying stream. SoapFormatter
uses a quite similar process.
Note Recall that the XmlSerializer does not persist a type’s fully qualified name or the name of the defining
assembly; this behavior helps keep the state of the object as mobile as possible. This type is concerned only with
persisting exposed public data.
Beyond moving the required data into and out of a stream, formatters also analyze the members in
the object graph for the following pieces of infrastructure:
•
A check is made to determine whether the object is marked with the
[Serializable] attribute. If the object is not, a SerializationException is thrown.
•
If the object is marked [Serializable], a check is made to determine whether the
object implements the ISerializable interface. If this is the case, GetObjectData()
is called on the object.
795