使用Protobuf-Net,Unexpected子类型在运行时创建TypeModel

时间:2011-10-10 13:14:51

标签: serialization protobuf-net

我有下面的类结构,并希望在运行时使用Protobuf-Net对其进行序列化。不幸的是我收到错误“Unexpected sub-type:Web2Pdf”。为什么呢?

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

1 个答案:

答案 0 :(得分:2)

子类型必须与立即父级关联,因此:EntityBase需要了解WebEntity,而WebEntity需要了解{{1} (而不是Web2Pdf知道两者和EntityBase不了解WebEntity)。

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

此外,这可以通过Web2Pdf完成,如果子类型号是固定的,这可能会更方便。

相关问题