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

发布于 2024-12-09 10:49:53 字数 953 浏览 0 评论 0原文

我有下面的类结构,并希望使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风吹过旳痕迹 2024-12-16 10:49:53

子类型必须与直接父级关联,因此:EntityBase需要了解WebEntity,并且WebEntity需要了解 Web2Pdf(而不是 EntityBase 了解两者,而 WebEntity 不了解 Web2Pdf)。

仅供参考,较小的标签编号也更有效 - 但取决于您。

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

The subtypes must be associated with the immediate parent, so: EntityBase needs to know about WebEntity, and WebEntity needs to know about Web2Pdf (rather than EntityBase knowing about both and WebEntity not knowing about Web2Pdf).

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文