反序列化时字节数组大小错误

本文关键字:错误 数组 字节数 字节 反序列化 | 更新日期: 2023-09-27 18:30:48

我正在使用protobuf-net序列化程序,到目前为止,它的功能已经完美。我有一个案例,一些私有整数成员必须序列化,但它们必须在序列化之前收集在一个字节数组中,然后在反序列化时从字节数组中提取,但在反序列化时字节数组的大小会发生变化。

在下面的代码中,我通过拥有一个包含整数的类来简化和说明这个问题,并且在序列化时,它通过 getter 访问,该 getter 将其转换为长度为 4 的字节数组。在 derserilization 时,该过程被逆转,但为资源库分配了一个大小是大小 (8) 的字节数组,这会导致错误。这种转换是不可能的吗?

请注意,大小为 8 的字节数组中的最后四个条目实际上包含序列化的值。为什么?

PrivateValue返回的数组是:[54, 100, 0, 0]但反序列化时给出的数组是:[0, 0, 0, 0, 54, 100, 0, 0]

[ProtoBuf.ProtoContract]
class SerializeTest
{
    public int Value { get; set; }
    [ProtoBuf.ProtoMember(1)]
    private byte[] PrivateValue
    {
        get
        {
            return new byte[4]
            {
                (byte)(Value),
                (byte)(Value >> 8),
                (byte)(Value >> 16),
                (byte)(Value >> 24)
            };
        }
        set
        {
            // For some reasone is the given byte array is always twice the size
            // and all the values are in the last part og the array
            this.Value = ((int)value[3] << 24) | ((int)value[2] << 16) | ((int)value[1] << 8) | value[0];
        }
    }
    public override string ToString()
    {
        return this.Value.ToString();
    }
}
class Program
{
    static void Main(string[] args)
    {
        var a = new SerializeTest() { Value = 25654 };
        using (var memStream = new MemoryStream())
        {
            // Serialize
            ProtoBuf.Serializer.Serialize(memStream, a);
            memStream.Position = 0;
            // Deserialize
            var data = ProtoBuf.Serializer.Deserialize<SerializeTest>(memStream);
            // Writs 0 and not 25654
            Console.WriteLine(data.Value);
        }
    }
}

反序列化时字节数组大小错误

经过进一步的研究,我在SO的字节数组上发现了这篇文章protobuf-net OverwriteList,它解释了它是protobuf中的一个错误,应该在未来的版本中解决。

我的猜测是它也序列化了Value字段。 尝试将其标记为忽略,看看是否有帮助:

[ProtoIgnore]
public int Value { get; set; }