gpt4 book ai didi

c# - 如何使用 ProtoBuf-Net 序列化继承类

转载 作者:IT王子 更新时间:2023-10-29 04:22:01 38 4
gpt4 key购买 nike

如果这是重复的,我很抱歉。我已经在几个地方搜索了我可能理解的答案,包括:

ProtoBuf.net Base class properties is not included when serializing derived class

Serialize inherited classes using protobuf-net

很抱歉,我并没有真正理解答案。我正在寻找一种更快、更紧凑的二进制序列化程序,而 ProtoBuf 看起来可能就是答案。我需要序列化一组全部派生自单个基类的类。它们的数量很多,所以在提交编辑类代码之前,我运行了一个简单的测试。此外,我不想以任何可能影响反序列化使用 NET 二进制序列化程序生成的旧持久文件的方式修改类。

这是基类:

[ProtoContract]
public class BaseClass
{
[ProtoMember(1)]
public string Name
{
get; set;
}
[ProtoMember(2)]
public int Age
{
get; set;
}
}

这是派生类:

[ProtoContract]
public class SubClass1 : BaseClass
{
[ProtoMember(3)]
public string Town
{
get; set;
}

[ProtoMember(4)]
public Sex Sex
{
get; set;
}
}

这是序列化和反序列化的代码(直接取自入门指南

var person = new SubClass1 { Age = 25, Name = "Fred", Town = "Denbigh", Sex = Sex.Female };

using (var file = File.Create(filename))
{
Serializer.Serialize(file, person);
}

和反序列化:

SubClass1 newPerson;
using (var file = File.OpenRead(filename))
{
newPerson = Serializer.Deserialize<SubClass1>(file);
}

MessageBox.Show(newPerson.Name +
" : " + newPerson.Town +
" : " + newPerson.Age.ToString() +
" : " + newPerson.Sex);

结果是“: Denbigh : 0 : Female”

不知何故,基类属性的值没有被序列化?我最初使用派生类的 ProtoMember 索引作为 1、2 对其进行了测试。我有点认为这行不通,所以选择了 3、4。这似乎没有什么区别。在我的偏执狂中,我使用标准 NET 二进制序列化程序运行了相同的测试并得到了预期的结果:“Fred : Denbigh : 25 : Female”

请问我错过了什么?

最佳答案

您需要在基类上使用 ProtoInclude 属性:

[ProtoContract]
[ProtoInclude(500, typeof(SubClass1 ))]
public class BaseClass
{

id arg(上例中的 500)对于该类应该是唯一的。参见 this文章了解更多信息

关于c# - 如何使用 ProtoBuf-Net 序列化继承类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12988964/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com