序列化包含列表的对象时ProtoBuf-net无效行为

问题描述 投票:0回答:1

我很难在下面的例子中解释行为:

[ProtoContract]
public class Class1Proto
{
    [ProtoMember(1)]
    public int data1 = 1;
    [ProtoMember(2)]
    public string data2 = "MYRANDOMSTRING";
}

[ProtoContract]
public class ProtoChunk
{
    [ProtoMember(1)]
    public List<Class1Proto> arr = new List<Class1Proto>();

    public const int PageSize = 4096;
}

用法:

    byte[] page = new byte[ProtoChunk.PageSize];

    ProtoChunk originalData = new ProtoChunk();
    for (int i = 0; i < 100; i++)
    {
        Class1Proto p = new Class1Proto();
        p.data1 = i * 2;
        p.data2 = (i * 2).ToString();
        originalData.arr.Add(p);
    }

    using (var memStream = new MemoryStream(page, writable:true))
    {
        Serializer.SerializeWithLengthPrefix(memStream, originalData, PrefixStyle.Fixed32);
    }

    using (var memStream = new MemoryStream(page, writable:false))
    {
        ProtoChunk deserializedData = Serializer.DeserializeWithLengthPrefix<ProtoChunk>(memStream, PrefixStyle.Fixed32);
    }

我的期望是originalDatadeserializedData应该是相同的。他们大多是除了deserializedData.arr[0].data1 == 1 while originalData.arr[0].data1 == 0。所有其他对象都是相同的,甚至包括originalData.arr[0].data2 and deserializedData.arr[0].data2(字符串字段)。

c# protocol-buffers protobuf-net
1个回答
3
投票

protobuf-net假设“隐含零默认值” - 即除非另有特定说明,成员的默认值为零,意味着:不传输零。这不是纯粹的任意 - 这实际上是“proto3”规范(好吧......或多或少;在“proto3”中,零是唯一允许的默认值)。

您的代码 - 特别是属性初始值设定项 - 的作用就像它的默认值为1一样,因此:当未传输零时,构造函数仍然会应用1,这就成为值(protobuf中的反序列化是“合并“操作 - 保留预先存在的值,同样符合规范)。

选项:

  • 告诉protobuf-net您的默认值 - 将[DefaultValue(1)]添加到该属性
  • 告诉protobuf-net不要运行构造函数(和属性初始化程序) - 将SkipConstructor = true添加到[ProtoContract]
  • 告诉protobuf-net不要假设这种行为:RuntimeTypeModel.Default.ImplicitZeroDefault = false;
  • 添加自己的条件序列化回调(如果你真的想要,我可以给出一个例子)

我亲自使用第一个选项。

© www.soinside.com 2019 - 2024. All rights reserved.