protobuf3 中的重复 Int32Value(可为空的 int 数组)

Repeated Int32Value in protobuf3 (nullable int array)

我有以下 protobuf 消息协议:

message TestMsg
{
  int32 int = 1;
  google.protobuf.Int32Value nullable_int = 2;
  repeated google.protobuf.Int32Value nullable_int_array = 3; // Runtime fail
}

protoc 编译得很好,在 C# 中所有 Int32Values 都是 int?。但它在运行时失败,并带有不允许的空参数异常。我可以理解 repeated 不允许空消息。但是 Int32Value 是 WellKnownType,因此如果需要,编译器可以生成特殊的 NullValue 类型。

这是 protobuf 的限制(不允许 repeated 中的 Int32Value)还是 C# 代码生成和支持库中的 limitation/bug?

除了创建您自己的消息和代码生成器之外,在 protobuf 协议中执行可为 null 的 int 数组的选项有哪些?

Is this a limitation in protobuf

是的。重复的 Int32Value 就像其他重复的消息一样工作:无法表示空值。请注意,在线路上,Int32Value 没有特殊处理,许多语言根本没有任何特殊处理。是的,这意味着 repeated Int32Value 字段毫无意义。这是一个 通用 语句,而不是任何特定于 C# 的语句。

如果您希望能够用一些空条目表示重复的字段,您需要创建一个包装包装器的消息:

message Int32ValueWrapper
{
    Int32Value value = 1;
}

... 然后有一个 repeated Int32ValueWrapper 字段。这将填充 Int32ValueWrapper 个元素,所有这些元素都将是非空的,但其中一些可能为空(因此 value 字段未填充)。

对于 C# 代码生成来说,这是一个棘手的情况,就它应该做什么而言...基本上是有点阻抗不匹配。