2012-04-05 45 views
3

我rx這個反序列化錯誤:反序列化列表<T>

線型無效;這通常意味着你覆蓋了一個文件而不會截斷或設置長度;看到Using Protobuf-net, I suddenly got an exception about an unknown wire-type

即只提到文件截斷,但我創建一個新的文件

Stopwatch sw = new Stopwatch(); 
      List<SomeClass> items = CreateSomeClass(); 
      sw.Start(); 
      using (var file = File.Create(fileName)) 
      { 
       var model = CreateModel(); 
       model.Serialize(file, items); 
       file.SetLength(file.Position); 
      } 
      sw.Stop(); 
      logger.Debug("Saving/serialization to {0} took {1} m/s", fileName, sw.ElapsedMilliseconds); 
      sw.Reset(); 
      logger.Debug("Starting deserialzation..."); 
      sw.Start(); 
      using (var returnStream = new FileStream(fileName, FileMode.Open)) 
      { 
       var model = CreateModel(); 
       var deserialized = model.Deserialize(returnStream, null, typeof(SomeClass)); 
      } 
      logger.Debug("Retrieving/deserialization of {0} took {1} m/s", fileName, sw.ElapsedMilliseconds); 

public static TypeModel CreateModel() 
    { 
     RuntimeTypeModel model = TypeModel.Create(); 

     model.Add(typeof(SomeClass), false) 
      .Add(1, "SomeClassId") 
      .Add(2, "FEnum") 
      .Add(3, "AEnum") 
      .Add(4, "Thing") 
      .Add(5, "FirstAmount") 
      .Add(6, "SecondAmount") 
      .Add(7, "SomeDate"); 
     TypeModel compiled = model.Compile(); 

     return compiled; 
    } 

public enum FirstEnum 
{ 
    First = 0, 
    Second, 
    Third 
} 
public enum AnotherEnum 
{ 
    AE1 = 0, 
    AE2, 
    AE3 
} 
[Serializable()] 
public class SomeClass 
{ 
    public int SomeClassId { get; set; } 
    public FirstEnum FEnum { get; set; } 
    public AnotherEnum AEnum { get; set; } 
    string thing; 
    public string Thing 
    { 
     get{return thing;} 
     set 
     { 
      if (string.IsNullOrEmpty(value)) 
       throw new ArgumentNullException("Thing"); 

      thing = value; 
     } 
    } 
    public decimal FirstAmount { get; set; } 
    public decimal SecondAmount { get; set; } 
    public decimal ThirdAmount { get { return FirstAmount - SecondAmount; } } 
    public DateTime? SomeDate { get; set; } 
} 

我是新來的protobuf網這樣有什麼明顯我做錯了/失蹤?

回答

2

您將它序列化爲一個列表,並將其反序列化爲一個單一項目。這是個問題。無論是使用DeserializeItems,或:不是

typeof(SomeClass) 

typeof(List<SomeClass>) 

的DeserializeItems可能稍快(由於種種原因,它必須做的時候反序列化是帶一個列表類型的額外工作操作數)。

+0

就是這樣感謝 – Eric 2012-04-05 21:43:26

+0

等待,這是否意味着 '[ProtoMember(10)] 公開名單 fUnits;' 將無法​​正常工作?我遇到了反序列化包含此字段的對象的錯誤。 – 2014-07-03 21:34:49

+0

@DavidDunham不,這並不意味着,無關 – 2014-07-03 22:27:54

1

鑑於錯誤似乎表明反序列化閱讀器想要讀取其他字節,請嘗試運行您的代碼而不使用file.SetLength(file.Position),這不應該被需要(文件流知道它的長度)。