Serialization: Store some objects into a file

  • Thread starter Thread starter Robert Schneider
  • Start date Start date
R

Robert Schneider

I would like to serialize some model objects into a file. For that I use the
BinaryFormatter. In order to not serialize the event delegates of those
objects (due to the observer pattern) I have implemented the ISerializable
interface where I use the GetValue and AddValue methods. So I do this
manually. This works fine. However, I see that the amount of model classes
increases. Now I find it anoying to write all those Add/GetValue methods.
It's quite boring and it's error-prone as well.

So my question is if there is another approach. Could it be solved more
elegant? Or what is the standard way to save something into a file?

Note that it is very important to me that I can realize versions. That is,
the model may change and older files must be still loadable (with some
convertions).

Thanks in advance,
Robert
 
It is possible to implement the GetObjectData method in a base class using
reflection to get all the members of the class. The complexity comes in with
complex inheritance trees as you would been to loop up the inheritence tree
serializing private members. You could also contrain yourself to making all
privates in the inheritence tree protected and then you would just be able to
serialize the current object by getting all its privates (which will include
all the protected's from parents).
The constuctor for serialization though has to be declard so you would need
to add a serialization contructor to every class which called the base class
version. e.g

public MyChildClass(SerializationInfo info, SerializationContext context) :
base(info,context){
//version specific conversions can be placed here
}

This isnt too bad for performance compared to the binary formatter as they
both use reflection.
I have a code sample I could dig out for the methods where all privates are
protected if you need it although it would be a good learning experience to
have a go yourself.

Ciaran O'Donnell
 
Back
Top