我很难在下面的例子中解释行为:
[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);
}
我的期望是originalData
和deserializedData
应该是相同的。他们大多是除了deserializedData.arr[0].data1 == 1 while originalData.arr[0].data1 == 0
。所有其他对象都是相同的,甚至包括originalData.arr[0].data2 and deserializedData.arr[0].data2
(字符串字段)。
protobuf-net假设“隐含零默认值” - 即除非另有特定说明,成员的默认值为零,意味着:不传输零。这不是纯粹的任意 - 这实际上是“proto3”规范(好吧......或多或少;在“proto3”中,零是唯一允许的默认值)。
您的代码 - 特别是属性初始值设定项 - 的作用就像它的默认值为1一样,因此:当未传输零时,构造函数仍然会应用1,这就成为值(protobuf中的反序列化是“合并“操作 - 保留预先存在的值,同样符合规范)。
选项:
[DefaultValue(1)]
添加到该属性SkipConstructor = true
添加到[ProtoContract]
RuntimeTypeModel.Default.ImplicitZeroDefault = false;
我亲自使用第一个选项。