protobuf-net 将基类反序列化为继承类
我有序列化的基类。
[ProtoContract]
public class Web2PdfEntity
{
[ProtoMember(1)]
public string Title { get; set; }
[ProtoMember(2)]
public string CUrl { get; set; }
}
我想将 Web2PdfEntity 类反序列化为从 Web2PdfEntity 继承的 Web2PdfServer 。
public class Web2PdfServer : Web2PdfEntity
{
public void MyServerMethod {}
public void MyServerMethod2{}
}
我尝试使用下面的代码来反序列化类,不幸的是未设置属性。
var web2Pdf = Serializer.Deserialize<Web2PdfServer>("c:\Web2PdfEntity-class-to-serialize-file.bin");
web2Pdf.Title //<- not deserialized
web2Pdf.CURL //<- not deserialized
I have base class which is serialized.
[ProtoContract]
public class Web2PdfEntity
{
[ProtoMember(1)]
public string Title { get; set; }
[ProtoMember(2)]
public string CUrl { get; set; }
}
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
(大量修改)
根据评论,提出的场景是:
Web2PdfEntity
并加载为Web2PdfServer
或 vv)这与正常用例略有不同,继承类型需要继承类型期间继承序列化(改变数据)和不相关的类型是可以互换的,只要合同合适。
有几种方法可以解决这个问题;一个小问题是,默认它不会查看继承的属性,以避免重复。您可以重新为它们做广告,但这有点笨拙。就个人而言,我认为我很想告诉它在应用程序启动期间要做什么:
现在您现有的
Serializer
代码将正确处理Web2PdfServer
,包括这两个属性表明的。(heavily revised)
Based on the comments, the scenario presented is:
Web2PdfEntity
and load asWeb2PdfServer
, or v.v.)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:
Now your existing
Serializer
code will treatWeb2PdfServer
correctly, including the two properties as indicated.