【发布时间】:2014-07-04 04:13:57
【问题描述】:
我在使用 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
第一次序列化产生一个空缓冲区,因此它第二次创建并清空集合对象。是否有任何机制可以正确处理这种情况以产生所需的序列化结果?
【问题讨论】:
标签: c# protobuf-net