c# - 关于继承的 ProtoBuf-Net 的问题?
问题描述
我想使用 protobuf 通过套接字连接用于协议。
我的问题是关于继承的。
假设我的项目中有以下类:
- 动物
- 猫(继承自动物)
- 狗(继承自动物)
比方说:
- Animal 继承自 Creature,它来自 DLL 中的一个类,我无法修改其代码(假设它是第 3 方库)。
- Cat 有 10 个字段,我为其赋予属性 ProtoMember 1 到 10。
- Dog as 12 个字段,所以我给 ProtoMember 1 到 12。
- Animal 有 5 个字段,所以我给 ProtoMember 1 到 5。
到目前为止,一切都很好。
为了处理继承,假设我在 Cat 上使用以下属性:
[ProtoInclude(11, typeof(Pet))]
在我使用的 Dog 上:
[ProtoInclude(13, typeof(Pet))]
关于动物使用:
[ProtoInclude(6, typeof(Creature))]
问题:
- 到目前为止我使用的这些数字都有效吗?如果不是,它们应该是什么,原因是什么?
- 我是否应该在 ProtoInclude 中给出一个空白(例如 111、113 和 106),以便允许将新字段添加到这些类中?或者我是否保持数字系列紧凑并在未来需要时进行调整?
所以要处理Creature的继承(哪些代码不在我的项目中),我相信我必须使用Runtime Type声明(这里提到:protobuf-net继承)
我不太确定这个示例需要哪些语句,以及这些语句需要放在我的项目中的什么位置?
任何帮助将不胜感激。谢谢你。
解决方案
[ProtoInclude]
从基类到子类工作-您需要注释基类型-因此:需要为andPet
声明[ProtoInclude(...)]
标记。同样,需要声明它期望. 显然,如果您不控制,这是一个问题,但如果这是一个问题,可以通过在运行时进行配置。就个人而言,我不建议使用您在序列化层次结构中无法控制的类型。Cat
Dog
Creature
Animal
Creature
RuntimeTypeModel
但是对于你的问题:
- 没关系,只要不与声明类型上的其他数字冲突即可;越低越便宜(
12
编码比 便宜34134923
) - 完全取决于你;常规字段和子类型字段是否交错都没有关系,所以有没有问题
[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, ...)] ...
}
推荐阅读
- android - Visual Studio 2019 Android - 意想不到的元素
在发现 - javascript - D3 Geojson Globe 在拖动和缩放期间在手机上的性能太差了
- docker - 最佳实践 - 匿名卷与绑定挂载
- python-3.x - 如何解决 Scipy 函数 fmintnc 中的值错误?
- matlab - MATLAB 编辑字段不接受打印值
- ios - 空的 UIStackView 导致高度/位置不明确
- android - 如何检查字符串是否包含 Windows .bat 文件中的子字符串
- plc - 结构化文本中的延迟计时器
- flutter - 当用户输入时,如何使 TextField 扩展?
- git - git reset --soft 奇怪的行为