【问题标题】:Protocol Buffers .NET inheritance协议缓冲区 .NET 继承
【发布时间】: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 中的此类数据(使用预编译,因为我使用的是轻量级框架)?

【问题讨论】:

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

标签: .net protocol-buffers protobuf-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); }

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

    【讨论】:

      猜你喜欢
      • 2017-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      • 2021-12-19
      • 2011-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多