gRPC 使用 Protobuf 作为其接口定义语言 (IDL)。 Protobuf IDL 是一种中性语言格式,用于指定 gRPC 服务发送和接收的消息。 Protobuf 消息在 .proto 文件中定义。 本文档介绍如何将 Protobuf 概念映射到 .NET。
有关 Protobuf 消息的详细信息,请参阅 Protobuf 语言指南

Protobuf 消息

消息是 Protobuf 中的主要数据传输对象。 它们在概念上类似于 .NET 类。

  1. syntax = "proto3";
  2. option csharp_namespace = "Contoso.Messages";
  3. message Person {
  4. int32 id = 1;
  5. string first_name = 2;
  6. string last_name = 3;
  7. }
  • 消息定义将三个字段指定为名称/值对。
  • 字段类型可以是 Protobuf 标量值类型(如 int32),也可以是其他消息。
  • Protobuf 样式指南建议使用 underscore_separated_names 作为字段名称。
  • 生成应用时,Protobuf 工具将从 .proto 文件生成 .NET 类型。 Person 消息生成 .NET 类
    1. public class Person
    2. {
    3. public int Id { get; set; }
    4. public string FirstName { get; set; }
    5. public string LastName { get; set; }
    6. }

    标量值类型

    Protobuf 支持一系列本机标量值类型。 下表列出了全部本机标量值类型及其等效 C# 类型:
Protobuf 类型 C# 类型
double double
float float
int32 int
int64 long
uint32 uint
uint64 ulong
sint32 int
sint64 long
fixed32 uint
fixed64 ulong
sfixed32 int
sfixed64 long
bool bool
string string
bytes ByteString

日期和时间

本机标量类型不提供与 .NET 的 DateTimeOffsetDateTimeTimeSpan 等效的日期和时间值。 可使用 Protobuf 的一些“已知类型”扩展来指定这些类型。 这些扩展为受支持平台中的复杂字段类型提供代码生成和运行时支持。
下表显示日期和时间类型:

.NET 类型 Protobuf 已知类型
DateTimeOffset google.protobuf.Timestamp
DateTime google.protobuf.Timestamp
TimeSpan google.protobuf.Duration

可为 null 的类型

C# 的 Protobuf 代码生成使用本机类型,如 int 表示 int32。 因此这些值始终包括在内,不能为 null。
对于需要显式 null 的值(例如在 C# 代码中使用 int?),Protobuf 的“已知类型”包括编译为可以为 null 的 C# 类型的包装器。 若要使用它们,请将 wrappers.proto 导入到 .proto 文件中,如以下代码所示:

  1. syntax = "proto3";
  2. import "google/protobuf/wrappers.proto";
  3. message Person {
  4. // ...
  5. google.protobuf.Int32Value age = 5;
  6. }
C# 类型 已知类型包装器
bool? google.protobuf.BoolValue
double? google.protobuf.DoubleValue
float? google.protobuf.FloatValue
int? google.protobuf.Int32Value
long? google.protobuf.Int64Value
uint? google.protobuf.UInt32Value
ulong? google.protobuf.UInt64Value
string google.protobuf.StringValue
ByteString google.protobuf.BytesValue