Heirarchical Serialization

  • Thread starter Thread starter Pete Davis
  • Start date Start date
P

Pete Davis

I haven't used Serialization support in .NET before and I have a few
questions about it.

let's assume the following:

class A : ISerializable
{
....
}

class B : A, ISerializable
{
private C cField;
....
}


class C: ISerializable
{
....
}


First of all, yeah, I'm missing the Serializable attributes here, and a lot
of other stuff, but this should be sufficient for my question..

In class B, how do I define GetObjectData()? I need to define it as new or
override? If it's "new" then from B.GetObjectData() do I simply call
base.GetObjectData() to deserialize the base class A? Does that work in a
"new" method?

What about the class C which is contained within B? In the
B(SerializationInfo, StreamingContext) constructor, do I simply do a cField
= new C(serInfo, context)? In B.GetObjectData() do I just call
cField.GetObjectData(serInfo, context)

Just not really sure how this all goes together. The above seems to make
sense to me except for whether or not B.GetObjectData should be new or
override. Of course, I could be completely off on all of it.

The other question is in regards to classes that aren't serializable. For
example, if I have a member that is a Font class, and I want to serialize
it, do I just take all of the pertinent data from the font object and
serialize those pieces that I need to re-create the font in the serializable
constructor?

Thanks

Pete
 
Pete,
Seeing as B inherits from A I would define B as:

class B : A
{
private C cField;
....

}

Then make GetObjectData virtual in A, allowing B to override it. In B's
override of GetObjectData I would call A's (base) GetObjectData.

Normally I make the ISerializable.GetObjectData method & the special
constructor protected as only the derived classes and the runtime need to
actually see them. (I use VB.NET, so making GetObjectData Protected is
easy).
What about the class C which is contained within B? In the
B(SerializationInfo, StreamingContext) constructor, do I simply do a cField
= new C(serInfo, context)? In B.GetObjectData() do I just call
cField.GetObjectData(serInfo, context)
No to both! You use SerializationInfo.GetValue so the runtime deserializes
the object in cField, remember the object in cField may be derived from C,
GetValue will handle it for you.

cField = (C)info.GetValue("cField", typeof(C));

In case you don't have them, the following articles provide a wealth of
information on serialization:

http://msdn.microsoft.com/msdnmag/issues/02/04/net/
http://msdn.microsoft.com/msdnmag/issues/02/07/net/
http://msdn.microsoft.com/msdnmag/issues/02/09/net/

Hope this helps
Jay
 
Back
Top