protobuf网继承 [英] protobuf-net inheritance

查看:392
本文介绍了protobuf网继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

马克计算器上提到,将有可能在protobuf网使用ProtoInclude属性(或类似的方法)序列化/反序列化的类层次的V2而无需指定在基类中的每个子类型。这是实现了吗?我们可以在外部库中导出一个插件接口,所以没有办法知道派生类型将是什么的方式。我们可以维持,虽然类型之间的唯一编号,但我无法在网络上找到任何的例子,短期使用的需要指定一个亚型ProtoInclude属性。

Marc mentioned on stackoverflow that it will be possible in v2 of protobuf-net to use ProtoInclude attribute (or similar approach) to serialize/deserialize class hierarchy without a need to specify each subtype in the base class. Is this implemented yet? We have a plugin interface that can be derived in external libraries, so there is no way of knowing what the derived types will be. We could maintain unique numbering between types though, but I couldn’t find any examples on the net, short of using ProtoInclude attribute which requires a subtype to be specified.

如何我会去实现与protobuf网继承一样,如果我不知道亚型是什么?

How would I go about implementing inheritance with protobuf-net like that if I don't know what the subtypes are?

推荐答案

如果您在属性不能指定亚型(因为它不是在编译时知道),你有2个选项(这两种只适用于V2,可作为测试版):

If you can't specify the subtypes in attributes (because it isn't known at compile-time) you have 2 options (both of which only apply to "v2", available as beta):


  1. 使用 RuntimeTypeModel ,而不是静态的串行方法(现在只是一个捷径 RuntimeTypeModel.Default );讲述继承(如下所示)模型

  2. DynamicType = TRUE 添加到 [ProtoMember(。 ..)] 问题

  1. use a RuntimeTypeModel, rather than the static Serializer methods (which are now just a short-cut to RuntimeTypeModel.Default); tell the model about the inheritance (example below)
  2. add DynamicType = true to the [ProtoMember(...)] in question

二是的的非常纯净的protobuf - 它嵌入类型信息,我真的不的,但人们只是 保存要求。首先是我的首选。在运行时添加亚型:

The second is not very pure protobuf - it embeds type information, which I don't really love but people just kept asking for. The first is my preferred option. To add subtypes at runtime:

var model = TypeModel.Create();
var type = model.Add(typeof(YourBaseType), true);
var subTypeA = model.Add(typeof(SomeSubType), true);
var subTypeB = model.Add(typeof(SomeOtherSubType), true);
type.AddSubType(4, typeof(SomeSubType));
type.AddSubType(5, typeof(SomeOtherSubType));



真正在上面的意思是使用正常的规则,自动添加成员属性 - 你还可以利用该控件并指定属性(等等),如果手动你喜欢

the true in the above means "use normal rules to add member properties automatically" - you can also take control of that and specify the properties (etc) manually if you prefer.

请注意,一个 TypeModel 应该被缓存和重新使用(而不是每个需要序列化对象创建的),因为它包含了一些发出代码来生成方法。重新使用它会更快,需要更少的内存。类型模型是线程安全的,并且可以用于序列化/在不同的线程同时反序列化的多个流

Note that a TypeModel should be cached and re-used (not created per object you need to serialize), as it includes some "emit" code to generate methods. Re-using it will be faster and require less memory. The type-model is thread-safe, and can be used to serialize/deserialize multiple streams concurrently on different threads.

这篇关于protobuf网继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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