How to change deserialization order using BinaryFormatter in C #?

Suppose I have a class A that contains a class B, and both are [Serializable].

I suggested that when deserializing, class B will first be deserialized.

However, this is not the case, as I could confirm, by simply logging in when all the [OnDeserialized] methods have been deleted.

Now I have the following problem:

After class A is deserialized, it must install itself using the values ​​from class B. Unfortunately, class B has not yet been deserialized, so classA is not configured correctly.

My problem will be solved if I can get BinaryFormatter to deserialize classB in front of class A or allow the diagram of objects from bottom to top and not top to bottom.

Another obvious solution would be to force classB to fire an event when it is deserialized, and then set class A, but I want to stay away from this not elegant solution.

Therefore, I would appreciate if anyone knows of a better solution.

+5
source share
4 answers

If you must have explicit control over the order of serialization and deserialization of objects, I suggest you implement an interface ISerializablefor A:

public class ClassA : ISerializable
{
    private ClassB _dependency;

    public ClassA(SerializationInfo information, StreamingContext context)
    {
        _dependency 
            = (ClassB)information.GetValue("_dependency", typeof(ClassB));

        // TODO: Get other values from the serialization info.
        // TODO: Set up stuff from dependent object.
    }

    public SerializationInfo GetObjectData()
    {
        information.AddValue("_dependency", _dependency, typeof(ClassB));

        // TODO: Add other fields to the serialization info.
    }
}
+3
source

I would suggest simply using the method marked [OnDeserialized]to handle any initialization after the serialization you require, and not refer to the order in which they are deserialized.

+1

These two steps can do the trick:

  • Make the [OnDeserialized]class B method safe to call multiple times.
  • In a [OnDeserialized]class A method, explicitly call the method [OnDeserialized]on the contained object of class B.

BinaryFormatterwill call the [OnDeserialized]class B object method again , but step 1 makes it safe.

0
source

All Articles