【问题标题】:Array mismatch on Deserialization with protobuf-net使用 protobuf-net 反序列化的数组不匹配
【发布时间】:2014-05-02 02:16:27
【问题描述】:

我是 protobuf-net 的完整初学者,所以这可能只是一些愚蠢的初学者错误。但我找不到这有什么问题:

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

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

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

}

和这样定义的测试:

        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);
            }
        }

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

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

我在这里犯了什么错误? 提前致谢!

【问题讨论】:

    标签: c# serialization protobuf-net


    【解决方案1】:

    必须将 RuntimeTypeModel 设置为支持 null

    请参阅以下帖子: How can I persist an array of a nullable value in 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);
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多