问题
We are using protobuf.net to serialize classes between mobile devices and back end services, but we now need to adjust what is sent back to the client based upon the 'context' of the user.
We would typically do this by implementing the ISerializable interface and look at the context value to then decide what to serialize. Similarly in the constructor we would then deserialize the provided values.
But it would appear that ISerializable isn't implemented/support (i can see why) for protobuf.net, so we have got around this by taking the 'ShouldSerialize*' and 'OnSerializing' approaches. This does however mean that we end up having to store the StreamingContext in each class which doesn't feel right. We could potentially stick it in a global but this also doesn't feel right.
Is there a better way to achieve what we want, e.g. serialization only using protobuf.net format but with what is serialized being influenced by an externally provided context?
回答1:
It is a good question. The patterns currently supported (ShouldSerialize* etc) are borrowed "as is" entirely from the BCL, hence no context - however there is no reason it can't support parameters in the same way that the callbacks do - indeed, for callbacks it supports pretty much any usage (with/without context etc) - so I can't think of a good reason not to support them here to.
You are right t say it isn't supported currently, but it could be - let me know of this would be useful.
来源:https://stackoverflow.com/questions/10190167/protobuf-net-conditional-serialization