使用 Protobuf-Net 在运行时创建 TypeModel,意外的子类型
我有下面的类结构,并希望使用 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; }
}
I have the class structure below and would like to serialize it at runtime using Protobuf-Net
. Unfortunately I get error "Unexpected sub-type: Web2Pdf". Why?
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; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
子类型必须与直接父级关联,因此:
EntityBase
需要了解WebEntity
,并且WebEntity
需要了解Web2Pdf
(而不是EntityBase
了解两者,而WebEntity
不了解Web2Pdf
)。仅供参考,较小的标签编号也更有效 - 但取决于您。
此外,这一切都可以通过 [ProtoInclude(...)] 来完成,如果子类型编号是固定的,这会更方便。
The subtypes must be associated with the immediate parent, so:
EntityBase
needs to know aboutWebEntity
, andWebEntity
needs to know aboutWeb2Pdf
(rather thanEntityBase
knowing about both andWebEntity
not knowing aboutWeb2Pdf
).For info, smaller tag numbers are more efficient, too - but up to you.
Additionally, this can all be done via
[ProtoInclude(...)]
, which can be more convenient if the sub-type numbers are fixed.