使用 ProtoBuf.net 的最新 2.0 beta 版本,我尝试序列化派生类(仅示例),但得到空文件。为什么基类属性没有序列化?
[ProtoContract]
[Serializable]
public class Web2PdfClient : Web2PdfEntity
{
}
[ProtoContract]
[Serializable]
public class Web2PdfEntity : EngineEntity
{
[ProtoMember(1)]
public string Title { get; set; }
[ProtoMember(2)]
public string CUrl { get; set; }
[ProtoMember(3)]
public string FileName { get; set; }
}
[ProtoContract]
[Serializable]
public class EngineEntity
{
public bool Result { get; set; }
public string ErrorMessage { get; set; }
public bool IsMembershipActive { get; set; }
public int ConversionTimeout { get; set; }
public byte[] FileStorage { get; set; }
}
在使用下面的代码序列化类时,我得到空文件。
var Web2PDF = new Web2PdfClient
{
CUrl = "http://www.google.com",
FileName = "test.txt"
};
using (var file = File.Create(@"C:\Users\Administrator\Projects\temp\test.bin"))
{
Serializer.Serialize(file, Web2PDF);
}
事实上,我很惊讶没有抛出异常 - 我会调查!为了使其发挥作用,基本类型必须有一种独特的方式来指示每个子类型。这可以通过属性指定,或者(在 v2 中)在运行时指定。例如:
[ProtoContract]
[Serializable]
public class Web2PdfClient : Web2PdfEntity
{
}
[ProtoContract]
[ProtoInclude(7, typeof(Web2PdfClient))]
[Serializable]
public class Web2PdfEntity : EngineEntity
{ ... }
没什么特别的7
但它不应与为该类型定义的任何其他成员发生冲突。可以定义多个子类型(使用不同的标签)。另请注意,protobuf-net 不看[Serializable]
,所以你不需要它,除非你也在使用BinaryFormatter
(或类似)。
相似地,EngineEntity
应该做广告its预期的子类型,并应指示要序列化的成员(以及针对哪个标签)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)