gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:13:02 25 4
gpt4 key购买 nike

我使用的是 protobuf-net 序列化程序,到目前为止,它运行良好。我有一个案例,一些私有(private)整数成员必须被序列化,但它们必须在序列化之前聚集在一个字节数组中,然后在反序列化时从字节数组中提取出来,但字节数组的大小在反序列化时发生了变化。

在下面的代码中,我通过一个包含整数的类简化并说明了这个问题,在序列化时,它通过一个将其转换为长度为 4 的字节数组的 getter 来访问。在反序列化过程中,过程是相反的,但是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);
}
}
}

最佳答案

经过进一步研究,我发现了这篇文章 protobuf-net OverwriteList on Byte Array SO上,说明是protobuf的bug,应该会在以后的版本中解决。

关于c# - 反序列化时字节数组大小错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10122730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com