我有下面的类结构,并希望使用 Protobuf-Net
在运行时对其进行序列化。不幸的是我收到错误“意外的子类型: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; }
}
最佳答案
子类型必须与直接父级关联,因此:EntityBase
需要了解WebEntity
和WebEntity
需要了解 Web2Pdf
(而不是 EntityBase
了解两者,而 WebEntity
不了解 Web2Pdf
)。
仅供引用,较小的标签编号也更高效 - 但取决于您。
此外,这一切都可以通过[ProtoInclude(...)]
来完成,如果子类型编号是固定的,这会更方便。
关于serialization - 使用 Protobuf-Net 在运行时创建 TypeModel,意外的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7713303/