2012-04-12 51 views
3

我使用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); 
     } 
    } 
} 
+0

memStream.Position = 0之後的memStream.Length是什麼? – SwDevMan81 2012-04-12 11:59:35

回答

2

經過進一步的研究,我發現SO這篇文章protobuf-net OverwriteList on Byte Array,這解釋說,這是在protobuf的一個bug,它應該在未來的版本中得到解決。

+1

是的,在代碼中修復;有沒有在公共建設中沒有出去?我目前的主要克隆目前有點骯髒,但我可以嘗試着重於儘快完成新的構建,而不是晚些時候 – 2012-04-12 13:35:15

0

我的猜測是它的序列化Value字段也是如此。嘗試將其標記爲忽略,看看是否有幫助:

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