Serialized objects disappearing (BinaryFormatter)

冷暖自知 提交于 2019-12-06 03:01:51

The array deserializes first and the inner deserilazations are performed afterwards. When looping through the array of ProfileModel its content haven' been derserialized yet.

You can probably fix this by implementing IDeserializationCallback (or by assigning the OnDeserilized attribute to a method that should be called upon deserilization completion). The OnDeserialzation method is called after the entire object graph is deserialized.

You would need to stash away your arrays in private fields:

private int []i1;
private int []i2;
private ProfileModel []  ipts;

Do the following under derserialization:

ipts = info.GetValue("ipts", typeof(ProfileModel[]));
i2 = info.GetValue("tp2", typeof(int[])) as int[];
i1 = info.GetValue("tp1", typeof(int[])) as int[];

And implement IDeserializationCallback:

public void OnDerserilization(object sender)
{
  PointProfiles = new Dictionary<Tuple<int, int>, IPointTrainingSet>();

  for (int i = 0; i < i1.Length; i++)
     PointProfiles.Add(new Tuple<int, int>(i1[i], i2[i]), ipts[i]);
}

I was able to get this to work by letting .NET handle List and Dictionary serialization instead of trying to do it manually:

void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
    info.AddValue("pca", PointPCA);
    info.AddValue("pps", PointProfiles);
    info.AddValue("am", AlignedMean);
    info.AddValue("transforms", Transforms);
    info.AddValue("fnames", FileNames);
}

public TrainingSet(SerializationInfo info, StreamingContext context)
{
    PointPCA = info.GetValue("pca", typeof(PrincipalComponentAnalysis)) as PrincipalComponentAnalysis;
    Transforms = (List<Tuple<string, ITransform>>)info.GetValue("transforms", typeof(List<Tuple<string, ITransform>>));
    AlignedMean = info.GetValue("am", typeof(double[])) as double[];
    PointProfiles = (Dictionary<Tuple<int, int>, IPointTrainingSet>)info.GetValue("pps", typeof(Dictionary<Tuple<int, int>, IPointTrainingSet>));
    FileNames = info.GetValue("fnames", typeof(string[])) as string[];
}

You have a very complex object graph. I tried breaking in the constructor of Profile and ProfileModel and had some strange results, but this simple version seems to work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!