protobuf 和 List
我有一个 List
I have a List<object>
with different types of objects in it like integers, strings, and custom types. All custom types are protobuf-adjusted.
What I wanna do now is to serialize / deserialize this list with protobuf.net. Up until now I suspect that I have to declare each and every type explicitly, which is unfortunately not possible with these mixed-list constructs. Because the binary formater has no problems to do these things I hope that I missed something and that you can help me out.
So my question is how to deal with objects in protobuf.net.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
(披露:我是 protobuf-net 的作者)
BinaryFormatter
是一个基于元数据的序列化器; 即它发送有关每个序列化对象的.NET 类型信息。 protobuf-net 是一个基于契约的序列化器(XmlSerializer
/DataContractSerializer
的二进制等价物,它也会拒绝这一点)。当前没有传输任意对象的机制,因为另一端无法知道您正在发送的内容; 但是,如果您想要发送一组已知不同的不同对象类型,则可能有其他选择。 管道中还有允许运行时可扩展模式(而不仅仅是在构建时固定的属性)的工作 - 但这还远未完成。
这并不理想,但它有效......当我完成支持运行时模式的工作时,它应该更容易:
(disclosure: I'm the author of protobuf-net)
BinaryFormatter
is a metadata-based serializer; i.e. it sends .NET type information about every object serialized. protobuf-net is a contract-based serializer (the binary equivalent ofXmlSerializer
/DataContractSerializer
, which will also reject this).There is no current mechanism for transporting arbitrary objects, since the other end will have no way of knowing what you are sending; however, if you have a known set of different object types you want to send, there may be options. There is also work in the pipeline to allow runtime-extensible schemas (rather than just attributes, which are fixed at build) - but this is far from complete.
This isn't ideal, but it works... it should be easier when I've completed the work to support runtime schemas:
有一种方法可以做到这一点,尽管不是一种非常干净的方法,即使用包装器对象,该包装器对象利用另一种支持任意对象的序列化机制。 我在下面使用 JSON 展示了一个示例,但正如我所说,采用不同的序列化工具似乎违背了使用 protobuf 的目的:
编辑:这也可以使用 C# 的内置二进制序列化来完成
There is a way of doing this, albeit not a very clean way, by using a wrapper object that utilises another serialisation mechanism that supports arbitrary objects. I am presenting an example below using JSON but, like I said, resorting to a different serialisation tool seems like defeating the purpose of using protobuf:
EDIT: This can also be done using C#'s built-in binary serialisation