Custom Serialization

Team Fly 

Page 79

There's a substantial overhead the first time you create an instance of the XmlSerializer class. This process, however, isn't repeated during the course of the application. The overhead is due to the fact that the CLR creates a temporary assembly for serializing and deserializing the specific type. This assembly, however, remains in memory for the course of the application and the initial overhead won't occur again. This means that, although there will be an additional delay of a couple of seconds when the application starts (or whenever you load the settings), you can persist the class with the application's configuration every time the user changes one of the settings without any performance penalty.

Custom Serialization

The .NET Framework makes it possible to override the default serialization process and take complete control of how your objects are serialized and deserialized. You may wish to control the serialization process if you want to serialize more than just public fields, but not every aspect of an object. To build classes that control their own serialization, you must first make sure that they implement the ISerializable interface:

 <Serializable( )> _ Public Class Employee     Implements ISerializable 

The ISerializable interface contains a single method, the GetObjectData method, whose signature is the following:

 Sub GetObjectData(ByVal info As SerializationInfo, _                   ByVal context As StreamingContext) 

The SerializationInfo class exposes the AddValue method, which adds members to the serialized object. This method accepts as argument a key–value pair, as demonstrated in the following sample code. The first three fields can be public or private. The last field, CreationDate, need not even be a member of the class—it's created and populated during the serialization. The custom deserializer can take this field's value into consideration, or ignore it completely.

 Private Sub GetObjectData(ByVal info As SerializationInfo, _                           ByVal context As StreamingContext)_                           Implements ISerializable.GetObjectData     info.AddValue(''classField1" , value1)     info.AddValue("classField2" , value2)     info.AddValue("classField3" , value3)     info.AddValue("CreationDate" , DateTime.Now()) End Sub 

The custom deserialization process is implemented as an overloaded form of the class's constructor, which has the following signature:

 Friend Sub New(ByVal info As SerializationInfo, _                ByVal context As StreamingContext) 
Team Fly 


Visual Basic  .NET Power Tools
Visual Basic .NET Power Tools
ISBN: 0782142427
EAN: 2147483647
Year: 2003
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net