Information Technology Reference
In-Depth Information
implement the IDeserializationCallback interface to initialize these non-
serializable members. IDeserializationCallback contains one method:
OnDeserialization. The framework calls this method after the entire object
graph has been deserialized. You use this method to initialize any non-
serialized members in your object. Because the entire object graph has
been read, you know that any function you might want to call on your
object or any of its serialized members is safe. Unfortunately, it's not fool-
proof. After the entire object graph has been read, the framework calls
OnDeserialization on every object in the graph that supports the
IDeserializationCallback interface. Any other objects in the object graph
can call your object's public members when processing OnDeserialization.
If they go first, your object's nonserialized members are null, or 0. Order
is not guaranteed, so you must ensure that all your public methods han-
dle the case in which nonserialized members have not been initialized.
So far, you've learned about why you should add serialization to all your
types: Nonserializable types cause more work when used in types that
should be serialized. You've learned about the simplest serialization meth-
ods using attributes, including how to initialize nonserialized members.
Serialized data has a way of living on between versions of your program.
Adding serialization to your types means that one day you will need to
read an older version. The code generated by the Serializable attribute
throws exceptions when it finds fields that have been added or removed
from the object graph. When you find yourself ready to support multiple
versions and you need more control over the serialization process, use the
ISerializable interface. This interface defines the hooks for you to cus-
tomize the serialization of your types. The methods and storage that the
ISerializable interface uses are consistent with the methods and storage
that the default serialization methods use. That means you can use the
serialization attributes when you create a class. If it ever becomes necessary
to provide your own extensions, you then add support for the ISerializable
interface.
As an example, consider how you would support MyType, version 2, when
you add another field to your type. Simply adding a new field produces a
new format that is incompatible with the previously stored versions on
disk:
[ Serializable ]
public class MyType
{
 
Search WWH ::




Custom Search