Obtaining a Types Serializable Members

Table 8-4 lists some of the methods that the FormatterServices class provides that facilitate writing custom serialization formatters.

Table 8-4: Significant Public Methods of System.Runtime.Serialization.FormatterServices

Method

Description

GetSerializableMembers

Obtains the serializable members for a given type

GetObjectData

Obtains the values for one or more serializable members of an object instance

GetUninitializedObject

Obtains an uninitialized object instance during deserialization

PopulateObjectMembers

Initializes an uninitialized object instance's members with values

In an example in the previous section, we defined the SomeClass2 type. The following code snippet demonstrates using each of the FormatterServices methods listed in Table 8-4 to obtain the serializable members and their values for a serializable instance of the SomeClass2 type:

SomeClass2 sc = new SomeClass2();

// Obtain the serializable members and their values. MemberInfo[] mi =

FormatterServices.GetSerializableMembers(sc.GetType());

object[] vals = FormatterServices.GetObjectData(sc,mi);

// Obtain an uninitialized object and populate its members. SomeClass2 sc2 =

(SomeClass2)FormatterServices.GetUninitializedObject(typeof (SomeClass2));

FormatterServices.PopulateObjectMembers(sc2,mi,vals);

The GetSerializableMembers method returns an array of System.Reflection.MemberInfo instances for a specified type. If you pass a type that isn't serializable to GetSerializableMembers, the common language runtime will raise a System.Runtime.Serialization.SerializationException exception. Note that passing a type implementing the ISerializable interface to the GetSerializableMembers method doesn't result in the GetSerializableMembers method calling ISerializable.GetObjectData. This means that you might not actually get all the serialization members that the type implementer intended.

To obtain the values for each serializable member, you pass the MemberInfo array to the GetObjectData method, which returns an object array whose elements correspond to the values for the serializable members. The two arrays are populated so that the /h element of the object array is the value of the member defined by the /h element in the Memberlnfo array.

To reverse the process we've just described, you create an uninitialized instance of the SomeClass2 type by using FormatterServices.GetUninitializedObject. The critical word here is uninitialized—the constructor isn't called, and members that reference other objects are set to null or 0. To initialize the uninitialized object instance, you use the PopulateObjectMembers method, passing it the uninitialized object instance, the Memberlnfo array describing each member you are initializing, and a matching object array with the values for the members. The return value of PopulateObjectMembers is the object being populated.

0 0

Post a comment