可以通过协议缓冲区发送可空类型吗?

pqu*_*est 10 c# protocol-buffers

Proto3 C#参考包含以下内容:

包装类型字段

proto3 中大多数众所周知的类型不会影响代码生成,但是包装器类型(StringWrapper、Int32Wrapper 等)会更改属性的类型和行为。

所有包装类型对应于C#值类型(的Int32WrapperDoubleWrapperBoolWrapper等等)被映射到 Nullable<T>哪里T是相应的非空类型。例如,类型的字段会生成类型DoubleValue为 的 C# 属性 Nullable<double>

类型的字段StringWrapperBytesWrapper在类型C#性能结果stringByteString产生,但与一默认值null,并允许null要被设置为属性值。

对于所有包装器类型,重复字段中不允许使用空值,但允许作为映射条目的值。

当试图生成一个.cs从文件.proto文件,如果我试图声明一个字段Int32Wrapper.proto的文件,protoc.exe抛出有关错误Int32Wrapper不存在。

syntax ="proto3";
package prototest;
import "MessageIdentifier.proto";


message TestMessage {
    string messageTest = 1;
    fixed64 messageTimestampTicks = 2;
    uint32 sequenceNumber = 3;
    MessageUniqueID uniqueID = 4;
    Int32Wrapper nullableInt = 5; 
}
Run Code Online (Sandbox Code Playgroud)

似乎这里缺少一些额外的步骤,有人知道如何启用这些类型吗?

zet*_*oot 15

我会尝试改进尼克的答案,因为它对我没有帮助。grpc 编译器声称他没有关于google.protobuf.Int32Wrapper类型的信息。我发现它实际上被称为google.protobuf.Int32Valuehttps://github.com/protocolbuffers/protobuf/blob/48234f5f012582843bb476ee3afef36cda94cb66/src/google/protobuf/wrappers.proto#L88),尽管谷歌确实称之为Int32Wrapper。所以帮助我的代码如下:

...
import "google/protobuf/wrappers.proto";
...
message TestMessage {
    ...
    google.protobuf.Int32Value nullableInt = 5; 
}
Run Code Online (Sandbox Code Playgroud)

其他链接:


Nic*_*ell 8

关于https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/wrappers.proto

您需要导入 google/protobuf/wrappers.proto 才能使其正常工作。

syntax ="proto3";
package prototest;
import "MessageIdentifier.proto";
import "google/protobuf/wrappers.proto";

message TestMessage {
    string messageTest = 1;
    fixed64 messageTimestampTicks = 2;
    uint32 sequenceNumber = 3;
    MessageUniqueID uniqueID = 4;
    google.protobuf.Int32Value nullableInt = 5; 
}
Run Code Online (Sandbox Code Playgroud)

然后您可以将其用作int?,例如 nullableInt.HasValue 和 nullableInt.Value