2016-08-11 53 views
1

我有一個列表的各種數據類型(DateTime,int,十進制,字符串)的對象。是否有可能序列化使用協議緩衝區的System.Object對象的列表

List<object> myObjects = new List<object>(); 
myObjects.Add(3); 
myObjects.Add(3.9m); 
myObjects.Add(DateTime.Now); 
myObjects.Add("HELLO"); 

我能夠使用序列化protobuf網這個名單,但總是反序列化拋出異常:「附加信息:不預期的類型,並沒有合同可以推斷出:System.Object的」。

using (var ms = new MemoryStream()) 
{ 
    Serializer.Serialize(ms, list2); 
    var bytes = ms.ToArray(); 
    ms.Position = 0; 
    var clone = Serializer.Deserialize(typeof(List<object>), ms); //Throws exception 
} 

我沒有任何明確的合同,我想這是問題嗎?但是,我確實知道序列化對象的預期類型,但我如何告訴protobuf-net?

回答

3

檢查這些,看看爲什麼這是很長的路要走:

  1. The need for a parameterless constructor

  2. why dynamic instead of object wouldn't have worked

  3. 爲什麼DynamicType=truewouldn't have worked

  4. the need for an abstract base class and concrete implementations,通過protobuf的創造者-net

  5. why no serializer for object

抽象基

[ProtoContract] 
    [ProtoInclude (1, typeof(ObjectWrapper<int>))] 
    [ProtoInclude(2, typeof(ObjectWrapper<decimal>))] 
    [ProtoInclude(3, typeof(ObjectWrapper<DateTime>))] 
    [ProtoInclude(4, typeof(ObjectWrapper<string>))] 
    abstract class ObjectWrapper { 
     protected ObjectWrapper() {} 
     abstract public object ObjectValue { get; set; } 
    } 

實施

[ProtoContract()] 
    class ObjectWrapper<T> : ObjectWrapper 
    { 
     public ObjectWrapper(): base() { } 
     public ObjectWrapper(T t) { this.Value = t; } 

     [ProtoIgnore()] 
     public override object ObjectValue 
     { 
      get { return Value; } 
      set { Value = (T)value; } 
     } 

     [ProtoMember(1)] 
     public T Value { get; set; } 
    } 

測試

 var myObjects = new List<ObjectWrapper>(); 
     myObjects.Add(new ObjectWrapper<int>(3)); 
     myObjects.Add(new ObjectWrapper<decimal>(3.9m)); 
     myObjects.Add(new ObjectWrapper<DateTime> (DateTime.Now)); 
     myObjects.Add(new ObjectWrapper<string> ("HELLO")); 
     var clone = Serializer.DeepClone(myObjects); 
相關問題