gpt4 book ai didi

c# - 从 C# 读取 protobuf3 自定义选项

转载 作者:行者123 更新时间:2023-12-04 19:38:24 25 4
gpt4 key购买 nike

TL;博士

根据文档,如果我在做 C++,我可以使用 string value = MyMessage::descriptor()->options().GetExtension(my_option); 读取自定义选项的值。 . Java 和 Python 也有类似的例子。但我正在做 C#,我可以找到一个等价的。我可以做吗,如果可以,怎么做?

更多详情

我正在操作由 protobuf3 生成的类.模式声明了 custom option .它看起来像这样:

import "google/protobuf/descriptor.proto";

extend google.protobuf.MessageOptions {
string my_option = 51234;
}

message MyMessage {
option (my_option) = "Hello world!";
}

我的代码提供了一个从 MyMessage 生成的对象,我想阅读此选项的值(此处 Hello world!)

更新:我没有使用 protobuf-net。现在 protobuf 原生支持 C#,我正在使用 Google 的 protobuf3 C# 库。

最佳答案

您现在可以在 C# 中访问自定义选项。首先,在你的 .proto 中定义自定义选项:

import "google/protobuf/descriptor.proto";
extend google.protobuf.FieldOptions {
string objectReferenceType = 1000; //Custom options are 1000 and up.
}

接下来,将自定义选项应用于某些内容。在这里,我将其附加到一个字段:
message Item
{
string name = 1;
int32 id = 2;
string email = 3;
ObjectReference prefab = 4 [(objectReferenceType) = "UnityEngine.GameObject"];
}

然后您需要查找自定义选项字段编号。没有好的方法可以做到这一点,因此只需从您定义自定义选项扩展名的文件的 FileDescriptor 中查找扩展名。您将拥有一个 C# 生成的类,称为 protoFileNameReflection。从中,您可以找到扩展名,然后是字段编号。这是一个假设 proto 名为“Item.proto”的示例,因此生成的类称为 ItemReflection:
foreach (FieldDescriptor extensionFieldDescriptor in ItemReflection.Descriptor.Extensions.UnorderedExtensions)
{
if (extensionFieldDescriptor.ExtendeeType.FullName == "google.protobuf.FieldOptions")
{
objectReferenceTypeFieldNumber = extensionFieldDescriptor.FieldNumber;
break;
}
}

然后使用 protobuf 反射访问代码中的自定义选项:
FieldDescriptor fieldDescriptor = prefabFieldDescriptor;
CustomOptions customOptions = fieldDescriptor.CustomOptions;
if (customOptions.TryGetString(objectReferenceTypeFieldNumber, out string objectReferenceTypeText))
{
Console.Log(objectReferenceTypeText); //logs: "UnityEngine.GameObject"
}

关于c# - 从 C# 读取 protobuf3 自定义选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39116667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com