protobuf-net:如何在消息中表示继承并生成派生 类?

protobuf-net : how to represent inheritance in messages and generate derived classes?

protobuf-net proto2 c#

这是我的 .cs 文件,适用于 protobuf-net serialize/deserialize :

[ProtoBuf.ProtoContract(Name=@"MyBaseTypeProto")]
[ProtoBuf.ProtoInclude(typeof(MyDerivedType), 1)]
public partial class MyBaseType { ... }

[ProtoBuf.ProtoContract(Name=@"MyDerivedTypeProto")] 
public partial class MyDerivedType : MyBaseType { ... }

[ProtoBuf.ProtoContract(Name=@"MyMessageProto")]                                                                  
public partial class MyMessage                                          
{                                                                                               
    [ProtoBuf.ProtoMember(1, IsRequired = false, Name = @"MyList", DataFormat = ProtoBuf.DataFormat.Default)]                                                 
    public List<MyDerivedType> MyList;  

是否可以编写 .proto 文件以便 protogen.exe 生成以上内容?

类似于:

MyBaseType.proto
message MyBaseType {
    ...
}

MyDerivedType.proto
message MyDerivedType {
    ...
}

MyMessage.proto
import "MyDerivedType.proto"
message MyMessage{                                                                          
    repeated MyDerivedType MyList = 1;                                                          
}    

但应用于上述消息类型的 protogen.exe 不会根据需要生成上述 类;具体来说,它不会生成这些代码行:

[ProtoBuf.ProtoInclude(typeof(MyDerivedType), 1)]

public partial class MyDerivedType : MyBaseType

协议缓冲区不支持类似于(或映射到)C++/C# 中直观继承的形式的继承/Java。

here:

Messages can also be extended, but the method by which this is accomplished differs from familiar C++ or Java-style inheritance. Instead, message extension is implemented by reserving some number of field indices in the base message for use by the extending messages.

protocol buffer docs 说:

Extensions let you declare that a range of field numbers in a message are available for third-party extensions. Other people can then declare new fields for your message type with those numeric tags in their own .proto files without having to edit the original file.

第一篇文章还讨论了其他几种近似多态性的技术,以及每种技术的优缺点。