protobuf-net:如何注释派生类型的属性?

时间:2016-09-30 00:19:42

标签: c# inheritance serialization protocol-buffers protobuf-net

对于最新版本的protobuf-netr640文件夹),如何最好地注释作为派生类型的ProtoMember

[ProtoBuf.ProtoContract(Name=@"MyBaseTypeProto")]                                       
[Serializable]      
public partial class MyBaseType: ProtoBuf.IExtensible { ... }

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

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

我已尝试将DynamicType属性添加到ProtoMember属性,但无法识别。

我需要一个解决方案,可以从xml defs proto types生成类。理想情况下,这将通过注释到属性定义的属性来完成。

似乎可以使用protogen.exe根据包含.proto语句的消息类型defs(import文件)生成类:

package MyPackage;                                                          

import "MyDerivedTypeProto.proto";                                                          

message MyMessage{                                                                          
    repeated MyDerivedType MyList = 1;                                                          
}       

但是import语句显然对生成的C#类(.cs文件)没有影响,除了添加注释:

// Generated from: MyMessageProto.proto
// Note: requires additional types generated from: MyDerivedType.proto

1 个答案:

答案 0 :(得分:1)

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

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

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

应该这样做(未经测试,不适合合适的计算机)。关键的增加是基类型的[ProtoInclude]。我删除了[Serializable],因为protobuf-net真的不关心它。