首页 > 解决方案 > 关于继承的 ProtoBuf-Net 的问题?

问题描述

我想使用 protobuf 通过套接字连接用于协议。

我的问题是关于继承的。

假设我的项目中有以下类:

  1. 动物
  2. 猫(继承自动物)
  3. 狗(继承自动物)

比方说:

  1. Animal 继承自 Creature,它来自 DLL 中的一个类,我无法修改其代码(假设它是第 3 方库)。
  2. Cat 有 10 个字段,我为其赋予属性 ProtoMember 1 到 10。
  3. Dog as 12 个字段,所以我给 ProtoMember 1 到 12。
  4. Animal 有 5 个字段,所以我给 ProtoMember 1 到 5。

到目前为止,一切都很好。

为了处理继承,假设我在 Cat 上使用以下属性:

[ProtoInclude(11, typeof(Pet))]

在我使用的 Dog 上:

[ProtoInclude(13, typeof(Pet))]

关于动物使用:

[ProtoInclude(6, typeof(Creature))]

问题:

  1. 到目前为止我使用的这些数字都有效吗?如果不是,它们应该是什么,原因是什么?
  2. 我是否应该在 ProtoInclude 中给出一个空白(例如 111、113 和 106),以便允许将新字段添加到这些类中?或者我是否保持数字系列紧凑并在未来需要时进行调整?

所以要处理Creature的继承(哪些代码不在我的项目中),我相信我必须使用Runtime Type声明(这里提到:protobuf-net继承

我不太确定这个示例需要哪些语句,以及这些语句需要放在我的项目中的什么位置?

任何帮助将不胜感激。谢谢你。

标签: c#.netprotocol-buffersprotobuf-net

解决方案


[ProtoInclude]从基类到子类工作-您需要注释类型-因此:需要为andPet声明[ProtoInclude(...)]标记。同样,需要声明它期望. 显然,如果您不控制,这是一个问题,但如果这是一个问题,可以通过在运行时进行配置。就个人而言,我不建议使用您在序列化层次结构中无法控制的类型。CatDogCreatureAnimalCreatureRuntimeTypeModel

但是对于你的问题:

  1. 没关系,只要不与声明类型上的其他数字冲突即可;越低越便宜(12编码比 便宜34134923
  2. 完全取决于你;常规字段和子类型字段是否交错都没有关系,所以有没有问题
[ProtoInclude(4, Whatever)]
[ProtoInclude(7, WhateverElse)]
class Foo {
   [ProtoMember(1, ...)] ...
   [ProtoMember(2, ...)] ...
   [ProtoMember(3, ...)] ...
   [ProtoMember(5, ...)] ...
   [ProtoMember(6, ...)] ...
   [ProtoMember(8, ...)] ...
}

但我承认很多人更喜欢将两者分开 - 也许

[ProtoInclude(101, Whatever)]
[ProtoInclude(102, WhateverElse)]
class Foo {
   [ProtoMember(1, ...)] ...
   [ProtoMember(2, ...)] ...
   [ProtoMember(3, ...)] ...
   [ProtoMember(4, ...)] ...
   [ProtoMember(5, ...)] ...
   [ProtoMember(6, ...)] ...
}

推荐阅读