本文介绍了带有单例的 XmlSerialization的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

序列化问题继续...

我正在尝试序列化一个类,该类的实例在它们之间共享公共对象(各种绑定器).因此,对象 A、B、C 共享对象 Binder1,对象 D 和 E - Binder2,依此类推......我正在序列化对象 A、B、C、D、E.通常,这个活页夹对象是在构造函数中传递的——虽然不是与序列化器一起传递,因为它需要一个无参数的构造函数.

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 似乎有一些适用于单例的东西 - IObjectReference 接口,其中方法 GetRealObject 可用于返回对新创建的单例的引用.但是,看起来 XmlSerializer 并不关心这个接口.

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?

编辑:我几乎准备放弃这个问题,因为我刚刚发现了这个2006 年在论坛上讨论的问题(!!) 两个巨头@JonSkeet 和@MarcGravell 之间,答案基本上是否.以防万一情况在过去 7 年中发生了变化,我会将这个问题保留更长时间.

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.

推荐答案

我还没有找到一种使用 XmlSerializer 本地执行此操作的方法.我确实在 Jon Skeet 和 Marc Gravell 之间找到了一个旧线程基本上是说你不能像使用 ISerializable 和 IObjectReference 那样做这件事.

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:

  • 给 Binder 对象(即多个对象共享的公共对象)添加 Guid 字段
  • 在反序列化期间,使用静态字典并使用具有相同 Guid 的已注册 Binder 对象,或将新的 Binder 对象添加到静态字典中以供其他人链接.

这篇关于带有单例的 XmlSerialization的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-02 03:34