问题
Using Protobuf-Net, I see that it does not seem possible to deserialize a class without having a parameterless constructor or I may be missing something?
I don't want some of the classes with a parameterless constructor. Is there some kind of attributes that I could use or some other technique?
回答1:
protobuf-net depends currently on having a parameterless constructor to work.
However that constructor need not be public (it will use reflection if need be to invoke it) so you may be able to define the required private constructor just for use by protobuf-net (adding a comment as to why) and deal with specific serialization related issues there.
This keeps the rest of your api from being able to construct 'illegal' instances.
Marc points out that if you are talking about the outermost message object, you could also create the object yourself and call Serializer.Merge. But if it needs to create an object (because it currently has a null instance, or for new items in a list/array), then it looks for a default constructor.
回答2:
ShuggyCoUk is right about it using the parameterless constructor.
Just for completeness, though - if you are talking about the outermost message object, you could also create the object yourself and call Serializer.Merge
. But if it needs to create an object (because it currently has a null
instance, or for new items in a list/array), then it looks for a default constructor.
I suppose that I could also provide some markup in the attribute to say "just create a raw object via FormatterServices
", but this feels unnecessary (compared with a private parameterless constructor), and may not work on all platforms (Silverlight, CF, etc - being likely problems).
来源:https://stackoverflow.com/questions/1335687/is-it-possible-to-use-protobuf-net-with-a-class-without-a-parameterless-construc