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

标签 c# protocol-buffers protobuf-csharp-port protobuf-3

我有以下 protobuf 消息协议(protocol):

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# 代码生成和支持库中的限制/错误?

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

最佳答案

Is this a limitation in protobuf

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

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

message Int32ValueWrapper
{
    Int32Value value = 1;
}

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

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

关于c# - protobuf3 中的重复 Int32Value(可为空的 int 数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50775612/

相关文章:

json - 在 NodeJS 中将 Protobuf 响应转换为 JSON

java - Protocol buffer 无法解析具有多个大尺寸消息的单个 codeInputStream

uwp - Google.Protobuf 是否支持 .NET Core?

c# - windows phone中如何在页面之间传递多个数据

c# - Entity Framework 4 和 Poco 以及 Linq2Sql 性能

protocol-buffers - Protocol Buffer : does changing field name break the message?

c# - 如何在 C# 中为 protobuf map<string, string> 属性设置值

c# - .NET 应用程序的最佳调度程序?

c# - 为什么 QueueClient 不是一次性的

protocol-buffers - Protobuf InvalidProtocolBufferException 与一些字符串