【问题标题】:Serialization Collections with protobuf-net使用 protobuf-net 的序列化集合
【发布时间】: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


    【解决方案1】:

    目前,对象是要么集合数据对象。原始 protobuf 规范中没有任何重叠的空间。我的建议是:如果您需要存储其他数据,那么您应该 封装 一个集合而不是 injerit 一个集合,即而不是:

    • YourType : SomeCollection
      • 一些数据成员

    拥有:

    • 你的类型
      • 项目(某种列表)
      • 一些数据成员

    这会很好。

    未能抑制列表处理(并改用成员处理),但是:我的建议仍然是封装而不是继承。那么它应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多