问题
Serialization woes continue...
I'm trying to serialize a class, instances of which share between them common objects (a binder of sorts). So, objects A, B, C share object Binder1, and objects D and E - Binder2, and so on... I'm serializing objects A,B,C,D,E. Typically, this binder object is passed in a constructor - not with the serializer though, since it needs a parameterless constructor.
ISeriazable seems to have something that works for singletons - IObjectReference
interface, where the method GetRealObject
can be used to return a reference to the newly created singleton. But, it doesn't look like XmlSerializer
cares about this interface.
So, how should I go about serializing/deserializing these objects?
EDIT: I'm almost ready to give up on this question, since I just discovered this question discussed on a forum from 2006 (!!) between two giants @JonSkeet and @MarcGravell, where the answer is essentially no for XmlSerializer. I'll keep this question open for a bit longer just in case things have changed in the past 7 years.
回答1:
I haven't found a way to do this natively with XmlSerializer. I did find an old thread between Jon Skeet and Marc Gravell that basically says that you can't do this the same way that you could with ISerializable and IObjectReference.
The way I had to make this work was along the following lines:
- Add a Guid field to the Binder object (i.e. the common object shared by multiple objects)
- During deserialization, use a static Dictionary and either use an already registered Binder object with the same Guid or add a new Binder object to the static dictionary for others to link against.
来源:https://stackoverflow.com/questions/17667164/xmlserialization-with-a-singleton