协议缓冲区 .NET 继承

Posted

技术标签:

【中文标题】协议缓冲区 .NET 继承【英文标题】:Protocol Buffers .NET inheritance 【发布时间】:2012-11-21 13:20:44 【问题描述】:

我有协议缓冲区格式的数据,可以描述如下

message Sections 
    repeated Section sections = 1;


message Section 
    required uint32 type = 1;
    required bytes payload = 2;


message SectionType1 
    required int32 fieldType1 = 1;
    // ...


message SectionType2 
    required int32 fieldType2 = 1;
    // ...


message SectionType3 
    required int32 fieldType3 = 1;
    // ...

我正在使用 protobuf-net 库(+ protogen + 预编译)。 如何将此类数据反序列化为类似于

的 DTO
public class Sections

    public List<Section> Sections  get; 


public abstract class Section



public class SectionType1 : Section

    public int FieldType1  get; 


public class SectionType2 : Section

    public int FieldType2  get; 


public class SectionType3 : Section

    public int FieldType3  get; 

是否可以使用 .NET 中的此类数据(使用预编译,因为我使用的是轻量级框架)?

【问题讨论】:

协议缓冲区用于序列化信息——以扁平和顺序的方式。您应该将在此类事物中使用的任何类型视为“形状”,仅包含数据,不包含继承或行为。请参阅数据传输对象。 【参考方案1】:

为此,您必须手动进行 - 即拥有

[ProtoContract]
public abstract class Section

    [ProtoMember(1)] public int Type get;set;
    [ProtoMember(2)] public byte[] Payload get;set;

并手动处理其余部分。 protobuf-net 继承映射到 以下 .proto 架构之上:

message Section 
    optional SectionType1 Type1 = 1;
    optional SectionType2 Type2 = 2;
    optional SectionType3 Type3 = 3;

我们在哪里,说:

[ProtoInclude(1, typeof(SectionType1)]
[ProtoInclude(2, typeof(SectionType2)]
[ProtoInclude(3, typeof(SectionType3)]
public abstract class Section


【讨论】:

【参考方案2】:

只是想补充一下我的发现,我创建了 .proto 文件,其中包含一个基类和 20 个派生类。 我通过 protobuf-net r668\ProtoGen 生成了代码。 我按照上面列出的步骤操作,但仍然出现错误,找不到子类型。

只是通过点击和试用,我看到生成的代码对所有生成的类都有 global::ProtoBuf.IExtensible,我从所有生成的类中删除了这个加上以下 3 行 私有全局::ProtoBuf.IExtension 扩展对象; 全局::ProtoBuf.IExtension 全局::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing);

在此之后,错误没有出现。我不知道为什么它有帮助,但它确实有效。

【讨论】:

以上是关于协议缓冲区 .NET 继承的主要内容,如果未能解决你的问题,请参考以下文章

不支持 Protobuf-NET IExtensible 继承的解决方法

带有协议缓冲区的 ASP.NET WebApi - 错误处理

.Net 协议缓冲区到 JSON,JsonFormatReader 类不处理最外面的花括号?

协议缓冲区 c# (protobuf-net) Message::ByteSize

进出 XPathDocument 的协议缓冲区消息

使用协议缓冲区模拟泛型