我正在用 C# 编程 - 对这个 protobuf 东西还是很陌生
如果您有以下扩展 EnumValueOptions 的 proto 文件:
extend google.protobuf.EnumValueOptions {
string Value = 101;
bool AutoEnrol = 102;
}
Protobuf 将通过自动生成生成一个 EnumValueOptionsExtensions 类。
要访问它,请稍后/下方根据 C# 代码示例使用 EnumValueOptionsExtensions.Value 或 EnumValueOptionsExtensions.AutoEnrol。
然后在同一个或另一个 proto 文件中,使用以下内容创建一个枚举:
enum SystemRoleType {
ReservedRole = 0 [(Value) = "SystemRoleType.ReservedRole", (AutoEnrol) = false];
Administrator = 1001 [(Value) = "SystemRoleType.Administrator", (AutoEnrol) = false];
Editor = 1002 [(Value) = "SystemRoleType.Editor", (AutoEnrol) = false];
ContentCreator = 1003 [(Value) = "SystemRoleType.ContentCreator", (AutoEnrol) = false];
User = 1004 [(Value) = "SystemRoleType.ContentCreator", (AutoEnrol) = true];
}
同样,这将通过 protobuf 自动生成生成一个 SystemRoleTypeReflection 类。
然后在 C# 中,相应地包含您的命名空间(还包括:Google.Protobuf.Reflection),然后您可以在 C# 中执行以下操作
EnumDescriptor SystemRoleTypeTypeEnumDescriptor = SystemRoleTypeReflection.Descriptor.FindTypeByName<EnumDescriptor>(typeof(SystemRoleType).Name);
foreach (SystemRoleType system_role_type in Enum.GetValues(typeof(SystemRoleType)))
{
EnumValueDescriptor enum_value_descriptor = SystemRoleTypeTypeEnumDescriptor.FindValueByNumber((int)system_role_type);
var selector_value = enum_value_descriptor.GetOptions().GetExtension<string>(EnumValueOptionsExtensions.Value);
var auto_enrolment = enum_value_descriptor.GetOptions().GetExtension<bool>(EnumValueOptionsExtensions.AutoEnrol);
}
更新(2021-12-01):
我今天将一个小型 VS 解决方案放在一起,您可以在 Visual Studio Community 2022 (.Net 6 / C# 10) 中打开它并在控制台应用程序中运行示例:github.com/kibblewhite/EnumValueOptions-gRPC-Example