问题
I am using BinaryFormatter
to serialize a collection of objects of class A
stored in a System::Collections::Generic::List<A^>^
. I have added the [Serializable]
tag and have implemented ISerializable
in class A
(both GetObjectData
and the special constructor). When deserializing, I find that the list is deserialized and contains the same number of elements as was serialized. However, each of these elements is a null reference.
I've checked for thrown exceptions and am sure that it is not the case. I have checked to ensure that the special constructor of the form A(SerializationInfo ^info, StreamingContext context)
is called the correct number of times during deserialization but these re-constructed objects are not being referenced from the deserialized collection.
I also replaced the System::Collections::Generic::List<A^>^
with array<A^>^
and I'm still getting the same results. The array has the correct number of elements but each element is a null reference.
Anyone who has seen a similar problem? Any clues?
回答1:
The problem was that any objects referred to within child objects need not have been completely deserialized immediately after a GetValue
call. In my case, the generic List
had not yet been completely deserialized and so contained only null references. I finally used IDeserializationCallback
to execute code after the object graph had been completely deserialized.
回答2:
From your description it sounds like the items within your list are possibly non-serializable; if you have control over that class can you verify if it is also tagged as serializable?
Also, have you tried using an XmlFormatter to be able to visually check the serialized data to see just how it's being built? It might provide some insight into whether the problem is occuring during serialization or deserialization.
来源:https://stackoverflow.com/questions/1097797/custom-net-serialization-doesnt-seem-to-work