protobuf-net将基类反序列化为继承的类 [英] protobuf-net deserialize base class to inherited class

查看:111
本文介绍了protobuf-net将基类反序列化为继承的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有序列化的基类.

[ProtoContract]
public class Web2PdfEntity 
{   


        [ProtoMember(1)]
        public string Title { get; set; }
        [ProtoMember(2)]
        public string CUrl { get; set; }
}

我想将Web2PdfEntity类反序列化为从Web2PdfEntity继承的Web2PdfServer.

I would like to deserialize Web2PdfEntity class to Web2PdfServer which is inherited from Web2PdfEntity.

public class Web2PdfServer : Web2PdfEntity
{

public void MyServerMethod {}
public void MyServerMethod2{}
}

我尝试使用下面的代码反序列化类,不幸的是未设置属性.

I have tried to use code below to deserialize class, unfortunately the properties are not set.

var web2Pdf = Serializer.Deserialize<Web2PdfServer>("c:\Web2PdfEntity-class-to-serialize-file.bin");
web2Pdf.Title //<- not deserialized
web2Pdf.CURL //<- not deserialized

推荐答案

(经过大量修改)

根据评论,提出的方案是:

Based on the comments, the scenario presented is:

  • 有两种类型, happen 是C#中的子类
  • 在序列化中,我们只想在它们之间进行平面交换-没有继承代码(即您可以另存为Web2PdfEntity并加载为Web2PdfServer或v.v.)
  • there are two types, which happen to be subclasses in C#
  • in serialization, we just want to flatly swap between them - no inheritance code (i.e. so you can save as Web2PdfEntity and load as Web2PdfServer, or v.v.)

这与 normal 用例稍有不同,在常规用例中,继承的类型期望在序列化期间进行继承(这会更改数据),并且只要合同适合,不相关的类型就可以互换.

This is a little different to the normal use case, where inherited types expect inheritance during serialization (which changes the data), and unrelated types are interchangeable as long as the contract fits.

有两种方法可以解决此问题;一个小问题是默认情况下不会查看继承的属性,以避免重复.您可以重新发布它们,但这有点笨拙.就个人而言,我很想告诉自己在应用启动过程中该怎么做:

There are a couple of ways of approaching this; one minor issue is that by default it doesn't look at inherited properties, to avoid duplication. You could re-advertise them, but that is a bit ungainly. Personally, I think I'd be tempted to just tell it what to do during app-startup:

var metaType = RuntimeTypeModel.Default.Add(typeof(Web2PdfServer), false);
metaType.Add(1, "Title").Add(2, "CUrl");

现在您现有的Serializer代码将正确处理Web2PdfServer,包括所示的两个属性.

Now your existing Serializer code will treat Web2PdfServer correctly, including the two properties as indicated.

这篇关于protobuf-net将基类反序列化为继承的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆