问题
I've implemented a prevalence layer for Compact Framework (including a BinaryFormatter
-like serializer). I'd like to be able to serialize the compiler-generated classes that result from such things as lambdas and iterators where appropriate, so that if (for example) a lambda and its closed-over variables (that is, the display class instance) is added to an event on a serializable object, and all the closed-over variables are serializable, then the resulting object graph is still fully serializable.
It's acceptable if instances of these classes can only be deserialized by the exact same build of the binaries that they were serialized from -- the prevalence layer is mostly to provide durability should the application be terminated unexpectedly (power failure and device reboot are distinct possibilities), and the serialized data stream is not expected to be either forward or backward compatible, or even for that matter compatible across two compiles of the same source code -- everything of consequence will be sent up to a server when we next talk to it anyway, and we're not going to update while disconnected.
Is it reasonable in this limited context for my formatter to treat these compiler-generated classes as if they were serializable? The only alternative I see is to hand-implement what areotherwise compiler-supported patterns everywhere serializability is a concern, with consequences ranging from the overly verbose to the nearly unreadable.
回答1:
I see what you are getting at, but in my experience it is a much better idea to concentrate on serializing data, and handle the durability by rolling back/forward to a known state, perhaps using something like a local CQRS queue, or some other way of storing "how you got there".
Re the specific question, within the tight scope of the question (only working on the same build etc) I guess that should be OK, but it depends a lot on whether anything that is captured in those variables has no sensible serialization - i.e. something like a UI element (easily accidentally captured with an invisible this
) that cannot be reconstructed (os handles, etc). If it is isolated data (by which I mean: the graph is just data from within your own code - no unmanaged dependencies), then I guess it should be OK.
The other issue is that CF lacks much of the stronger reflection available in the full framework, that might make this a bit more awkward than it might be on regular framework (GetUninitializedObject for example). Probably doable, but a bit more work.
来源:https://stackoverflow.com/questions/4733018/lambdas-closed-over-variables-display-classes-serializability-and-prevalence