2011-10-10 12 views
2

我有下面的类结构,并且想在运行时使用Protobuf-Net对它进行序列化。不幸的是我收到错误“Unexpected sub-type:Web2Pdf”。为什么?在运行时使用Protobuf-Net创建TypeModel,意外的子类型

var web2PdfEntity = new Web2Pdf(); 
web2PdfEntity.Property1 = 1; 
web2PdfEntity.Property2 = 2; 
    web2PdfEntity.Property3 = 3; 

var model = TypeModel.Create(); 
model.Add(typeof (EntityBase), true).AddSubType(20000, typeof (WebEntity)).AddSubType(30000,typeof (Web2Pdf));     
model.CompileInPlace(); 



    using (var stream = new FileStream(@"C:\1.txt", FileMode.Create, FileAccess.Write, FileShare.None)) 
{ 
    model.Serialize(stream, web2PdfEntity); //Get exception here! 
} 


[ProtoContract] 
public abstract class EntityBase 
{ 
    [ProtoMember(1011)] 
    public int Property1 { get; set; } 
} 

[ProtoContract] 
public abstract class WebEntity : EntityBase 
{ 
    [ProtoMember(1012)] 
    public int Property2 { get; set; } 
} 

[ProtoContract] 
public sealed class Web2Pdf : WebEntity 
{ 
    [ProtoMember(1013)] 
    public int Property3 { get; set; } 
} 

回答

2

亚型必须与立即父母有关,所以:EntityBase需要了解WebEntity,并WebEntity需要了解Web2Pdf(而不是EntityBase知道关于这两个和WebEntity不知道有关Web2Pdf)。

有关信息,较小的标签号码也更有效 - 但由您决定。

此外,这可以通过[ProtoInclude(...)]完成,如果子类型号码是固定的,这可能更方便。

+2

为了进一步阐述Marc所说的...... AddSubType()返回的是被调用的同一个MetaType,所以你可以将AddSubType()调用链接到同一类型......你想要做一个模型[typeof(WebEntity )]。AddSubType(30000,typeof(Web2Pdf));设置一切... – damageboy