Serialization 使用Protobuf Net在运行时创建TypeModel,意外的子类型

Serialization 使用Protobuf Net在运行时创建TypeModel,意外的子类型,serialization,protobuf-net,Serialization,Protobuf Net,我有下面的类结构,希望在运行时使用Protobuf-Net对其进行序列化。不幸的是,我得到了错误“意外的子类型:Web2Pdf”。为什么? 子类型必须与直接父级关联,因此:EntityBase需要了解WebEntity,WebEntity需要了解Web2Pdf(而不是EntityBase同时了解和WebEntity不了解Web2Pdf) 对于信息,更小的标签号也更有效-但取决于你 此外,这一切都可以通过[ProtoInclude(…)]来完成,如果子类型编号是固定的,这会更方便。进一步阐述Mar

我有下面的类结构,希望在运行时使用
Protobuf-Net
对其进行序列化。不幸的是,我得到了错误“意外的子类型:Web2Pdf”。为什么?


子类型必须与直接父级关联,因此:
EntityBase
需要了解
WebEntity
WebEntity
需要了解
Web2Pdf
(而不是
EntityBase
同时了解和
WebEntity
不了解
Web2Pdf

对于信息,更小的标签号也更有效-但取决于你


此外,这一切都可以通过
[ProtoInclude(…)]
来完成,如果子类型编号是固定的,这会更方便。

进一步阐述Marc所说的。。。AddSubType()返回调用它时使用的同一元类型,因此可以将AddSubType()调用链接到同一类型。。。你想做一个模型[typeof(WebEntity)]。AddSubType(30000,typeof(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; }
}