2013-04-22 57 views
1
[Serializable] 
[ProtoContract] 
public class DataWrapper 
{ 
    [ProtoMember(1)] 
    public double[] Data = new double[] { 1, 2, 3, 4 }; 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 

     Dictionary<int, DataWrapper> serialized = new Dictionary<int, DataWrapper>(); 
     Dictionary<int, DataWrapper> deserialized;// = new Dictionary<int, OHLC>(); 
     for (int i = 0; i < 10; i++) 
     { 
      serialized.Add(i, new DataWrapper());     
     } 
     using (FileStream ms = new FileStream("dictionary", FileMode.Create, FileAccess.Write)) 
     { 
      Serializer.Serialize<Dictionary<int, DataWrapper>>(ms, serialized); 
     } 


     using (FileStream ms = new FileStream("dictionary", FileMode.Open, FileAccess.Read)) 
     { 
      deserialized = Serializer.Deserialize<Dictionary<int, DataWrapper>>(ms); 
     } 

     Console.WriteLine("serialized {0} and deserialized {1}", serialized[0].Data.Length, deserialized[0].Data.Length); 

     } 
} 

我期待反序列长度为4的阵列,而我收到长度8的数组这是一个错误,或者我在做一个错误在这里?PortoBuf净反序列的序列化双阵列的两倍大小的版本

请注意,代码是没有意义的。这只是一个尝试来解释我在真实场景中遇到的问题

+0

DLL版本是2.0.0.622 – mustafabar 2013-04-22 10:22:12

回答

1

我不是Protobuf-net专家,但这似乎与this issue有关。我怀疑这是由于你明确初始化了double[]有4个元素,而protobuf-net在反序列化过程中“附加”了附加的4个元素。

作为一种变通方法,您可以设置SkipConstructor=trueProtoContract的选项,然后它的作品如您所愿:

[ProtoContract(SkipConstructor=true)] 
+0

'[ProtoMember(1,OverwriteList =真)] '也会做这项工作。看起来它不是一个bug,而是一个设计决定,因为Protobuf规范说如果数组不是空的,它应该被*追加。这对C#来说不是太“习惯”,因为变异数组的大小通常被认为是不好的做法。 – Groo 2017-08-11 15:48:39