Reputation: 26971
I have the following class:
[Serializable]
public class A : ISerializable
{
List<B> listOfBs = new List<B>();
public A()
{
// Create a bunch of B's and add them to listOfBs
}
public A(SerializationInfo info, StreamingContext context)
{
listOfBs = (List<B>)info.GetValue("listOfBs",typeof(List<B>))
listOfBs.Remove(x=>x.s==5)
}
}
and
[Serializable]
public class B : ISerializable
{
public int s;
public B(int t)
{
s=t;
}
public B(SerializationInfo info, StreamingContext context)
{
s = info.GetInt32("s");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("s",s);
}
}
The problem the line listOfBs.Remove(x=>x.s==5)
throws an exception because B's de-serialization constructor doesn't run until A's is done.
When I step through the code, A's listOfBs is just an entry of NULL objects matching how many B's are actually in listOfBs
How does one solve this de-serialization sequence issue?
Upvotes: 1
Views: 70
Reputation: 27913
Implement IDeserializationCallback. IDeserializationCallback.OnDeserialization
is called when deserialization is complete for the whole object graph.
I believe class A would be the best place to implement it, and you would put your problem code in A.OnDeserialization
as follows.
[Serializable]
public class A : ISerializable, IDeserializationCallback
{
List<B> listOfBs = new List<B>();
public A()
{
// Create a bunch of B's and add them to listOfBs
}
public void OnDeserialization()
{
listOfBs.Remove(x=>x.s==5)
}
}
Upvotes: 2