初始化 Google Protobuf RepeatedField 集合

Initialize Google Protobuf RepeatedField collections

当您尝试初始化已生成的 Google Protobuf 消息类型的重复字段成员 (属性) 时,您不能使用 setter,因为它们是只读的.

如何初始化 google Protobuf 消息的 RepeatedField 集合?

repeated.proto 文件生成的集合 property/member 是只读的。一旦您新建了生成的 protobuf 类型的实例,它们就会被初始化。由于它是一个只读集合,您不能将它设置为另一个实例,但您可以向已创建的实例添加元素。

您需要使用 Google Protobuf .net 库的扩展方法(对我来说这不直观,因为在撰写本文时我没有在 VS 2019 中获得 IntelliSense 支持)这样做。

例如,如果你的 protobuf 生成的类型是 Price,它恰好有一个重复的 field/collection 提升,比如 repeated Promotion promotions = <some int> 那么你会做

var price = new Price(); //just placeholder for already generated message
//other code
var promotions = new List<Promotion>(); //List is just an example
//code to populate promotions 
price.Promotions.Add(promotions);

官方参考link

尽管语法有点奇怪,但实际上您可以在 RepeatedField 上的集合初始值设定项 中使用集合 ,如下所示:

var promotions = new List<Promotion>(); 
// code to populate promotions 
var price = new Price() { Promotions = { promotions } };

这是可行的,因为 RepeatedField 定义了一个自定义集合初始值设定项(Add 的重载需要 IEnumerable<T>)。

我想这是一种变通方法,因此这些字段可以在消息中声明 readonly,但仍可用于集合初始值设定项。