XmlSerializer 和 OnSerializing/OnSerialized 替代方案
我有各种复杂的对象,这些对象通常包含其他复杂对象的集合。有时我只想在需要时加载集合,因此我需要一种方法来跟踪集合是否已加载(空/空不一定意味着它尚未加载)。为此,这些复杂对象继承自一个类,该类维护已加载集合的集合。然后,我们只需在要跟踪的每个集合的 setter 中添加对函数的调用,如下所示:
public List<ObjectA> ObjectAList {
get { return _objectAList; }
set {
_objectAList = value;
PropertyLoaded("ObjectAList");
}
}
PropertyLoaded 函数更新一个集合,该集合跟踪已加载的集合。
不幸的是,这些对象在 Web 服务中使用,因此被序列化(反序列化),并且所有 setter 都会被调用,并且 PropertyLoaded 会在实际上没有被调用时被调用。
理想情况下,我希望能够使用 OnSerializing/OnSerialized,以便该函数知道它是否被合法调用,但是我们使用 XmlSerializer,所以这是行不通的。尽管我很想更改为使用 DataContractSerializer,但由于各种原因我目前无法这样做。
还有其他方法可以知道序列化是否发生吗?如果没有,或者是否有更好的方法来实现上述目标,而无需每次需要跟踪新集合时都添加额外的代码?
I have various complex objects that often have collections of other complex objects. Sometimes I only want to load the collections when they're needed so I need a way to keep track of whether a collection has been loaded (null/empty doesn't necessarily mean it hasn't been loaded). To do this, these complex objects inherit from a class that maintains a collection of loaded collections. Then we just need to add a call to a function in the setter for each collection that we want to be tracked like so:
public List<ObjectA> ObjectAList {
get { return _objectAList; }
set {
_objectAList = value;
PropertyLoaded("ObjectAList");
}
}
The PropertyLoaded function updates a collection that keeps track of which collections have been loaded.
Unfortunately these objects get used in a webservice and so are (de)serialized and all setters are called and PropertyLoaded gets called when it actually hasn't been.
Ideally I'd like to be able to use OnSerializing/OnSerialized so the function knows if its being called legitimately however we use XmlSerializer so this doesn't work. As much as I'd like to change to using DataContractSerializer, for various reasons I can't do that at the moment.
Is there some other way to know if serialization is happening or not? If not or alternatively is there a better way to achieve the above without having to extra code each time a new collection needs to be tracked?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
XmlSerializer
不支持序列化回调。不过,你有一些选择。例如,如果你想选择是否序列化一个名为ObjectAList
的属性,你可以添加一个方法:如果你在反序列化过程中也需要知道,你可以使用:(
尽管你可能会发现 - 我可以不确定 - 仅在
true
情况下调用set
)当然,另一个选项是实现
IXmlSerialized
,但是这只能作为最后的手段。这并不有趣。XmlSerializer
does not support serialization callbacks. You have some options, though. For example, if you want to choose whether to serialize a property calledObjectAList
, you can add a method:If you need to know during deserialization too, you can use:
(although you might find - I can't be sure - that the
set
is only called for thetrue
case)The other option, of course, is to implement
IXmlSerializable
, but that should only be done as a last resort. It isn't fun.