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

3
我正在使用protobuf-net序列化器,目前为止,它一直运行得很好。我有一个情况,其中一些私有整数成员必须被序列化,但在序列化之前它们必须被收集到一个字节数组中,然后在反序列化时从字节数组中提取出来,但是字节数组的大小在反序列化时会发生变化。
在以下代码中,我通过包含一个整数的类简化和说明了这个问题,当进行序列化时,它通过getter访问并将其转换为长度为4的字节数组。在反序列化时,该过程被反转,但setter被分配了两倍大小(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);
        }
    }
}

在调用 memStream.Position = 0; 后,memStream.Length 是多少? - SwDevMan81
2个回答

2

经过进一步研究,我发现这篇SO文章解释说这是Protobuf中的一个bug,应该在未来版本中解决。


1
是的,在代码中已经修复了;那个问题还没有在公共版本中发布吗?我的当前主要克隆版本有点不干净,但我会尽快专注于发布一个新版本。 - Marc Gravell

0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接