我正在使用protobuf-net序列化器,目前为止,它一直运行得很好。我有一个情况,其中一些私有整数成员必须被序列化,但在序列化之前它们必须被收集到一个字节数组中,然后在反序列化时从字节数组中提取出来,但是字节数组的大小在反序列化时会发生变化。
在以下代码中,我通过包含一个整数的类简化和说明了这个问题,当进行序列化时,它通过getter访问并将其转换为长度为4的字节数组。在反序列化时,该过程被反转,但setter被分配了两倍大小(8)的字节数组,这导致错误。不可能进行这种类型的转换吗?
请注意,大小为8的字节数组中的最后四个条目实际上包含被序列化的值。为什么?
由PrivateValue返回的数组是:[54, 100, 0, 0],但在反序列化时给出的数组是:[0, 0, 0, 0, 54, 100, 0, 0]。
在以下代码中,我通过包含一个整数的类简化和说明了这个问题,当进行序列化时,它通过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