解析 proto3 中的 RepeatedFields

Parsing RepeatedFields in proto3

一个简单的'Person'对象被解析为

            Person person = new Person
            {
                Id = 1,
                Name = "Foo",
                Email = "foo@bar",
                Phones = { new Person.Types.PhoneNumber { Number = "555-1212" } }
            };
            using (MemoryStream stream = new MemoryStream())
            {
                // Save the person to a stream
                person.WriteTo(stream);
                bytes = stream.ToArray();
            }
            Person copy = Person.Parser.ParseFrom(bytes);

如何解析 RepeatedField<>?

编辑:问题是 RepeatedFields 是否可以通过线路发送,还是必须捆绑在消息中才能传递?

Person 是一条消息,因此您可以读取和写入它的单个实例,如您的示例所示。 repeated Person 消息中的字段,而不是消息本身。您不能 read/write 重复字段,您必须一次 read/write 整条消息。 (查看 the Python implementation,编码器似乎需要知道消息的长度才能对其进行正确编码,所以这是有道理的。)

但是,对于您所描述的情况,还有几种替代方案:

  1. 您可以发送一堆 Person 消息,然后在接收端以您需要的任何方式将它们聚集在一起。

  2. 您可以定义一条消息,我们称之为 People,包含一个字段 repeated Person 并编写该消息。在 documentation for encoding 中,他们注意到连接两个消息的字符串或调用 Message::MergeFrom 方法都会连接消息中的重复字段。因此,您可以发送任意数量的 People 消息并在接收端连接或合并它们。这将为您提供一条 People 消息,其中包含已发送的每个 Person,而无需预先知道将发送多少 Person 消息。