是否可以在没有无参数构造函数的类中使用Protobuf-Net? [英] Is it possible to use Protobuf-Net with a class without a parameterless constructor?

查看:71
本文介绍了是否可以在没有无参数构造函数的类中使用Protobuf-Net?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Protobuf-Net,我发现在没有无参数构造函数的情况下似乎无法反序列化类,否则我可能会遗漏某些东西吗?

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?

推荐答案

protobuf-net当前依赖于使用无参数构造函数来工作.

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.

这使您的api其余部分无法构造非法"实例.

This keeps the rest of your api from being able to construct 'illegal' instances.

Marc指出,如果您在谈论最外层的消息对象,则还可以自己创建该对象并调用Serializer.Merge.但是,如果需要创建一个对象(因为它当前有一个空实例,或者用于列表/数组中的新项),那么它将寻找默认的构造函数.

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.

这篇关于是否可以在没有无参数构造函数的类中使用Protobuf-Net?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆