我使用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