[英]Serialization Collections with protobuf-net
我在使用protobuf-net序列化通用集合时遇到一些问题。 这些类的定义如下:
[ProtoContract]
public class DOPerson
{
public DOPerson() { }
[ProtoMember(1)]
public string FirstName { get; set; }
[ProtoMember(2)]
public string Surname { get; set; }
}
[ProtoContract]
public class DOPersonCollection : DOCollection<DOPerson>
{
public DOPersonCollection() : base() { }
}
[ProtoContract]
public abstract class DOCollection<T> : BindingList<T>
{
public DOCollection() { }
[ProtoMember(100)]
public Guid CollectionGuid { get; set; }
}
为了测试序列化,我具有以下主要功能:
class Program
{
static void Main(string[] args)
{
DOPerson personOne = new DOPerson() { FirstName = "One", Surname = "Person" };
DOPerson personTwo = new DOPerson() { FirstName = "Two", Surname = "Person" };
DOPerson personThree = new DOPerson() { FirstName = "Three", Surname = "Person" };
DOPersonCollection personCollection1 = new DOPersonCollection();
personCollection1.CollectionGuid = Guid.NewGuid();
personCollection1.Add(personOne);
personCollection1.Add(personTwo);
personCollection1.Add(personThree);
// Searialize the Collection
MemoryStream memBuffer = new MemoryStream();
Serializer.Serialize(memBuffer, personCollection1);
// Deserialize the Collction
memBuffer.Position = 0;
DOPersonCollection personCollection2 = Serializer.Deserialize<DOPersonCollection>(memBuffer);
Console.WriteLine(string.Format("Person Collection 1 GUID : {0}", personCollection1.CollectionGuid.ToString()));
Console.WriteLine(string.Format("Person Collection 1 Count: {0}", personCollection1.Count));
Console.WriteLine("");
Console.WriteLine(string.Format("Person Collection 2 GUID : {0}", personCollection2.CollectionGuid.ToString()));
Console.WriteLine(string.Format("Person Collection 2 Count: {0}", personCollection2.Count));
Console.ReadLine();
}
}
产生的结果如下:
人员集合1 GUID:db4ff817-db79-4588-98af-d730800add2e人员集合1计数:3
人员收集2 GUID:00000000-0000-0000-0000-000000000000人员收集2计数:0
第一次序列化会产生一个空缓冲区,因此第二次创建并清空集合对象。 是否有任何机制可以正确处理这种情况以产生所需的序列化结果?
在当前,对象可以是一个集合或数据对象。 原始protobuf规范中没有重叠的空间。 我的建议是:如果您需要存储其他数据,则应该封装一个集合而不是添加一个集合,即代替:
拥有:
这将正常工作。
有一种不能抑制列表处理(和使用成员处理,而不是),而是:我的建议仍然封装而不是继承。 然后它应该工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.