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