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

标签 serialization protobuf-net

我有下面的类结构,并希望使用 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需要了解WebEntityWebEntity 需要了解 Web2Pdf(而不是 EntityBase 了解两者,而 WebEntity 不了解 Web2Pdf)。

仅供引用,较小的标签编号也更高效 - 但取决于您。

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

关于serialization - 使用 Protobuf-Net 在运行时创建 TypeModel,意外的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7713303/

相关文章:

algorithm - 反序列化给定格式的树?

c# - 在 ProtoBuf-net 中序列化 List<List<string>> 并反序列化为 C++ vector <vector<string>>

c# - 在 protobuf-net 中继承序列化

c# - 对于新的 .net 核心应用程序,我应该在 protobuf-net 和 google.protobuf 之间使用什么 NuGet 包?

c# - 使用 newton json 在 c# 中从反序列化的 json 转换错误

c++ - 使用 Xerces C++ 对 DOM 部分进行 XML 序列化

ios - Objective-C 会序列化/恢复具有多个引用的对象会创建重复的对象吗?

c# - 使用 Json.net 反序列化混合类型列表

c# - 在运行时 ProtoBuf-net 模型中是否允许使用 <T>?

c# - Protobuf-net 和泛型