2012-11-21 52 views
2

我具有可以如下协议缓冲器.NET继承

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网库(+硫辛酸+预编译)来描述在协议缓冲区格式的数据。 我如何反序列化这样的数据转换成类似

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; } 
} 

的DTO是否有可能与.NET这样的数据的工作(使用预编译,因为我在一个小型框架)?

+0

协议缓冲区用于序列化信息 - 以平面和顺序的方式。你应该将任何类型的东西都看作“形状”,只包含数据,不包含继承或行为。请参阅数据传输对象。 –

回答

0

为了做到这一点,你必须手动做到这一点 - 即有

[ProtoContract] 
public abstract class Section 
{ 
    [ProtoMember(1)] public int Type {get;set;} 
    [ProtoMember(2)] public byte[] Payload {get;set;} 
} 

和手动处理其余部分。 protobuf网继承地图顶部的以下 .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 
{ 
} 
0

只想添加我的发现,我创建了一个具有基础.proto文件类和20个派生类。 我通过protobuf-net r668 \ ProtoGen生成了代码。 我遵循上面列出的步骤,但我仍然收到错误,未找到子类型。

只是通过命中和试用,我看到生成的代码具有全局:: ProtoBuf.IExtensible针对所有生成的类,我删除了这个加上从所有生成的类中的3行以下 private global :: ProtoBuf.IExtension extensionObject; global :: ProtoBuf.IExtension global :: ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) {return global :: ProtoBuf.Extensible.GetExtensionObject(ref extensionObject,createIfMissing); }

之后这个错误没有来。我不知道它为什么帮助,但它的工作。