开发者

XmlSerializer and OnSerializing/OnSerialized alternatives

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 DataCont开发者_StackOverflow中文版ractSerializer, 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?


XmlSerializer does not support serialization callbacks. You have some options, though. For example, if you want to choose whether to serialize a property called ObjectAList, you can add a method:

public bool ShouldSerializeObjectAList () { /* logic */ }

If you need to know during deserialization too, you can use:

[XmlIgnore]
public bool ObjectAListSpecified {
    get { /* logic whether to include it in serialization */ }
    set { /* logic to apply during deserialization */ }
}

(although you might find - I can't be sure - that the set is only called for the true case)

The other option, of course, is to implement IXmlSerializable, but that should only be done as a last resort. It isn't fun.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜