2012-04-12 89 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; }