问题
Is it possible to (de)serialize a POCO type using neither protobuf-net attributes nor explicitly adding types into the model?
回答1:
At the moment - in short, no. It needs to have a basic understanding of how you intend it to operate. I guess maybe I could add something to let you specify a default strategy for completely unadorned types (things that aren't DataContract
, ProtoContract
or XmlType
), but the most appropriate option there would be "all public members" (much like XmlSerializer
).
The reason I don't want to encourage this is that it is brittle. Because of how the protobuf spec is defined, all you get is field-numbers. It is easy enough to say "ok, order them alphabetically and use their positions", but that is not safe if you ever want to change the type. And let's face it, we all do. You'd be amazed how often I add an AardvarkCount
property, which messes with alphabetical orderings.
Hence, I don't want to make it easy to get people into a position where they risk data integrity. Because I don't like people shouting at me. If there was a global default policy, it would be easy to use that policy without realising it, which is when you start getting into trouble.
I do, however, intend making it easier to choose those strategies on a per-type basis (the code all exists, it just isn't in the public API) - for example:
model.Add(typeof(MyCrazyType), false).ApplyPolicy(ImplicitFields.AllPublic);
(the ImplicitFields
stuff already exists, back to v1 days) or maybe just:
model.Add(typeof(MyCrazyType), ImplicitFields.AllPublic);
any help? does the reasoning make sense?
回答2:
I doubt it. What integer id's would it use for the properties?
You could of course write some reflection based code that adds the types to the model without manually specifying the configuration. But I imagine you'll get versioning problems when you add/remove properties from your types. Since I see no way to create a stable mapping from strings to integers implicitly.
You probably could also define some key-value format inside protobuf so you can use string keys instead of integer keys. But then you lose the advantages protobuf offers. And you could just use json/bson instead.
回答3:
What CodesInChaos is saying is true, about model changes likely breaking things, but for simpler projects or where models are stable, you can do that effectively. Here's how: https://github.com/danielcrenna/protobuf-poco
来源:https://stackoverflow.com/questions/6212075/how-poco-deserialization-works-in-protobuf-net