使用 protobuf-net 生成 类 时解码自定义选项值

Decode custom option values when classes are generated with protobuf-net

我正在使用 protogbuf-gen 转换 C# 类中的原型文件。 我想 convert proto 文件中的一些 option 到我的 类 上的一些 attribute . 所以我有一个带有如下选项的原型文件:

syntax = "proto3";

import "google/protobuf/timestamp.proto";
import "google/protobuf/descriptor.proto";

enum LogOrder {
    NONE = 0;
    FIRST = 1;
    SECOND = 2;
    THIRD = 3;
}

extend google.protobuf.FieldOptions {
    LogOrder shouldBeLogged = 50001;
}

message Person {
    string  id = 1 [(shouldBeLogged)=FIRST];
    int32 business_id = 2 [(shouldBeLogged)=SECOND,deprecated=true];
...

为了尝试这样做,我必须编写自己的 CSharpCodeGenerator 子类,在其中我可以用重载的 WriteField 中的属性装饰字段,.

public class ServiceCodeGenerator : CSharpCodeGenerator
{
    protected override void WriteField(GeneratorContext ctx, FieldDescriptorProto obj, ref object state, OneOfStub[] oneOfs)
    {
        var bytes = obj.Options?.ExtensionData;
        // if extension data == shouldBeLogged then write somee attribute with a value

        base.WriteField(ctx, obj, ref state, oneOfs);
    }
...

但是,我唯一能得到的是一个字节数组,其中包含类似 [136, 181, 24, 1] 的内容,其中最后一个字节“1”似乎是 "shouldBeLogged" 的值。

如何将这些字节转换为开发人员友好的内容,或以其他方式访问选项及其值?

如果您 运行 通过 protogen 现有的 .proto,您应该在生成的代码中得到:

public static class Extensions
{
    public static LogOrder GetshouldBeLogged(this global::Google.Protobuf.Reflection.FieldOptions obj)
        => obj == null ? default : global::ProtoBuf.Extensible.GetValue<LogOrder>(obj, 50001);

    public static void SetshouldBeLogged(this global::Google.Protobuf.Reflection.FieldOptions obj, LogOrder value)
        => global::ProtoBuf.Extensible.AppendValue<LogOrder>(obj, 50001, value);

}

这意味着您可以使用:

var shouldBeLogged = obj.Options.GetshouldBeLogged();