vendredi 14 août 2015

C# Dictionary inside IDeserializationCallback OnDeserialization not working

I deserialize a Dictionary like this:

public class StaticClass
{
  public static StaticClass instance;
  public Dictionary<string, ObjectSettings> objectSettingsDict;

  void ReadSettings()
  {
  IFormatter formatter = new BinaryFormatter();
  FileStream stream = new FileStream( fileName, FileMode.Open );
  objectSettingsDict = formatter.Deserialize( stream ) as Dictionary<string, ObjectSettings>;
  stream.Close();
  }
}

inside the ObjectSettings class i have:

public class ObjectSettings : ISerializable, IDeserializationCallback
{
   string otherObjectName;
   ObjectSettings otherObject;

   public ObjectSettings(SerializationInfo info, StreamingContext context)
   {
      otherObjectName = (string)info.GetValue( "otherObjectName", typeof( string ) );
   }

   public void GetObjectData(SerializationInfo info, StreamingContext context)
   {
      info.AddValue( "otherObjectName", otherObjectName, typeof( string ) );
   }

   void IDeserializationCallback.OnDeserialization(object sender)
   {
      // my problem: objectSettingsDict is null here:
      otherObject = StaticClass.instance.objectSettingsDict[otherObjectName];
   }
}

my real code is much more complicated...

in this simplified version i can clearly see that objectSettingsDict is null in the OnDeserialization.

i know that in this simplified version the problem could be solved by serializing otherObject instead of otherObjectName and let the .NET resolve the references.

my question is:

what would be the correct way to use a dictionary in the IDeserializationCallback.OnDeserialization function of the object that is serialized in this dictionary?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire