如何序列化继承类具有protobuf网 [英] How to Serialize Inherited Class with ProtoBuf-Net
问题描述
我很抱歉,如果这是一个重复。我已经搜索几个地方寻找答案,我能明白其中包括:
I am sorry if this is a duplicate. I have searched several places for an answer that I might understand including:
的 ProtoBuf.net Base类的属性不包括当序列化派生类
我道歉,但我并没有真正理解的答案。我找了一个更快更紧凑的二进制序列和protobuf的看起来似乎是答案。我需要序列化一组从单一基类派生类。有这么犯编辑类代码我跑了一个简单的测试之前,大量的人。 。此外,我不希望以任何方式修改可能影响反序列化老年与NET二进制序列产生持久文件中的类
My apologies but I did not really understand the answers. I am looking for a faster more compact binary serializer and ProtoBuf looks like it might be the answer. I need to serialize a set of classes that all derive from a single base class. There are a large number of them so before committing to edit the class code I ran a simple test. Also I do not want to modify the classes in any way that might impact deserializing older persisted files generated with the NET binary serializer.
这是基类:
[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;
}
}
这是代码序列化和反序列化(直接取从入门指南
This is the code to serialize and deserialize (taken directly from the Getting Started Guide
var person = new SubClass1 { Age = 25, Name = "Fred", Town = "Denbigh", Sex = Sex.Female };
using (var file = File.Create(filename))
{
Serializer.Serialize(file, person);
}
和德-serialize:
and de -serialize:
SubClass1 newPerson;
using (var file = File.OpenRead(filename))
{
newPerson = Serializer.Deserialize<SubClass1>(file);
}
MessageBox.Show(newPerson.Name +
" : " + newPerson.Town +
" : " + newPerson.Age.ToString() +
" : " + newPerson.Sex);
结果是:登比:0:女
不知何故从基类属性的值没有被序列化?我原来的ProtoMember指数派生类测试它作为1,2,我样的想法,不会让工作去了3,4,这似乎没有什么区别。在我的偏执狂,我跑使用标准NET二进制序列相同的测试,得到了预期的结果:弗雷德:登比:25:女
Somehow the values from the base class properties are not being serialized? I originally tested it with the ProtoMember indices for the derived class as 1, 2. I kind of thought that would not work so went for 3, 4. It seems to make no difference. In my paranoia I ran the same test using the standard NET binary serializer and got the expected result: "Fred : Denbigh : 25 : Female"
我在想什么吗?
推荐答案
您需要使用 ProtoInclude
属性上的基础类:
You need to use the ProtoInclude
attribute on your base class:
[ProtoContract]
[ProtoInclude(500, typeof(SubClass1 ))]
public class BaseClass
{
的ID精氨酸(500在上面的例子)应该是唯一的那类。请参见这文章以了解更多信息。
The id arg (500 in the above example) should be unique to that class. See this article for more information
这篇关于如何序列化继承类具有protobuf网的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!