我使用protobuf-net串化器,直到现在,它的功能已经完美。我有一种情况,一些私有整数成员必须被序列化,但它们必须在序列化之前在字节数组中收集,然后在反序列化中从字节数组中提取,但字节数组的大小在反序列化时被改变。在反序列化中字节数组大小的错误
在下面的代码中,我简化了一个包含整数的类,并说明了这个问题,在序列化时,通过一个getter将其转换为一个长度为4的字节数组。在derserilization过程中,但是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 2012-04-12 11:59:35