使用protobuf-net进行反序列化时阵列不匹配

Mik*_*ikk 2 c# serialization protobuf-net

我是protobuf-net的初学者,所以这可能只是一些愚蠢的初学者错误.但我无法找到这个问题:

我有一个类被序列化到磁盘定义如下:

[ProtoContract]
public class SerializableFactors
{
    [ProtoMember(1)]
    public double?[] CaF {get;set;}

    [ProtoMember(2)]
    public byte?[] CoF { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

和测试定义如下:

        if (File.Exists("factors.bin"))
        {
            using (FileStream file = File.OpenRead("factors.bin"))
            {
                _factors = Serializer.Deserialize<SerializableFactors>(file);
            }
        }
        else
        {
            _factors = new SerializableFactors();
            _factors.CaF = new double?[24];
            _factors.CaF[8] = 7.5;
            _factors.CaF[12] = 1;
            _factors.CaF[18] = 1.5;
            _factors.CoF = new byte?[24];
            _factors.CoF[8] = 15;
            _factors.CoF[12] = 45;
            _factors.CoF[18] = 25;
            using (FileStream file = File.Create("factors.bin"))
            {
                Serializer.Serialize(file, _factors);
            }
        }
Run Code Online (Sandbox Code Playgroud)

所以基本上如果文件不存在,我创建一个具有默认值的对象并将其序列化为磁盘.如果文件存在,我会将其加载到内存中.

但是我加载文件的结果不是我在保存到磁盘之前创建的.我创建了长度为24的数组,它们在插槽8,12和18中具有值.但是反序列化对象具有长度为3的数组,其中包含我的值.

这里的错误是什么?提前致谢!

Dav*_*vid 5

您必须将RuntimeTypeModel设置为支持null

请参阅以下帖子: 如何在Protobuf-Net中保留可以为空的值的数组?

// configure the model; SupportNull is not currently available
// on the attributes, so need to tweak the model a little
RuntimeTypeModel.Default.Add(typeof(SerializableFactors), true)[1].SupportNull = true;

if (File.Exists("factors.bin"))
{
   using (FileStream file = File.OpenRead("factors.bin"))
   {
      _factors = Serializer.Deserialize<SerializableFactors>(file);
   }
}
else
{
   _factors = new SerializableFactors();
   _factors.CaF = new double?[24];
   _factors.CaF[8] = 7.5;
   _factors.CaF[12] = 1;
   _factors.CaF[18] = 1.5;
   _factors.CoF = new byte?[24];
   _factors.CoF[8] = 15;
   _factors.CoF[12] = 45;
   _factors.CoF[18] = 25;
   using (FileStream file = File.Create("factors.bin"))
   {
     Serializer.Serialize(file, _factors);
   }
}
Run Code Online (Sandbox Code Playgroud)