协议缓冲区中的继承 [英] Inheritance in protocol buffers

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

问题描述

如何在 Google Protocol Buffers 3.0 中处理继承?

How to handle inheritance in Google Protocol Buffers 3.0?

Java 等效代码:

public class Bar {
    String name;
}
public class Foo extends Bar {
    String id;
}

Proto 等效代码是什么?

What would be Proto equivalent code?

message Bar {
    string name = 1;
}
message Foo {
    string id = 2;
}

推荐答案

Protocol Buffers 不支持继承.相反,请考虑使用组合:

Protocol Buffers does not support inheritance. Instead, consider using composition:

message Foo {
  Bar bar = 1;
  string id = 2;
}

但是,话虽如此,您可以使用一种类似于继承的技巧——但这是一种丑陋的技巧,因此您应该谨慎使用它.如果您定义消息类型,例如:

However, that said, there is a trick you can use which is like inheritance -- but which is an ugly hack, so you should only use it with care. If you define your message types like:

message Bar {
  string name = 1;
}
message Foo {
  string name = 1;
  string id = 2;
}

这两种类型兼容,因为Foo包含Bar字段的超集.这意味着如果您有一种类型的编码消息,您可以将其解码为另一种类型.如果您尝试将 Bar 解码为 Foo 类型,则不会设置字段 id(并将获得其默认值).如果将 Foo 解码为 Bar 类型,字段 id 将被忽略.(请注意,这些规则与在一段时间内向类型添加新字段时所适用的规则相同.)

These two types are compatible, because Foo contains a superset of the fields of Bar. This means if you have an encoded message of one type, you can decode it as the other type. If you try to decode a Bar as type Foo, the field id will not be set (and will get its default value). If you decode a Foo as type Bar, the field id will be ignored. (Notice that these are the same rules that apply when adding new fields to a type over time.)

您可以使用它来实现诸如继承之类的东西,方法是让几种类型都包含超类"字段的副本.但是,这种方法有几个大问题:

You can possibly use this to implement something like inheritance, by having several types all of which contain a copy of the fields of the "superclass". However, there are a couple big problems with this approach:

  • 要将Foo 类型的消息对象转换为Bar 类型,您必须进行序列化和重新解析;你不能只是投射.这可能效率低下.
  • 向超类添加新字段非常困难,因为您必须确保将字段添加到每个子类,并且必须确保这不会造成任何字段编号冲突.
  • To convert a message object of type Foo to type Bar, you have to serialize and re-parse; you can't just cast. This can be inefficient.
  • It's very hard to add new fields to the superclass, because you have to make sure to add the field to every subclass and have to make sure that this doesn't create any field number conflicts.

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

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