简单的“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是否可以通过电线发送,还是必须捆绑在要传递的消息中?
发布于 2016-01-27 14:51:56
Person是一条消息,因此您可以读取和写入它的单个实例,如您的示例所示。repeated Person是消息中的字段,而不是消息本身。您不能读取/写入重复字段,必须一次读取/写入整个消息。(看看Python实现,似乎编码器需要知道消息的长度才能正确编码,因此这是有意义的。)
但是,对于您描述的场景,有几种替代方案:
Person消息,并以所需的任何方式在接收端将它们聚集在一起。People,包含单个字段repeated Person并编写该消息。在编码文档中,他们注意到,连接两个消息的字符串或调用Message::MergeFrom方法都将连接消息中的重复字段。因此,您可以发送任意数量的People消息,并在接收端连接或合并它们。这将为您提供一条包含所发送的每个People消息的单个Person消息,而不必事先知道将发送多少Person消息。https://stackoverflow.com/questions/34871013
复制相似问题