2016-11-23 38 views
0

I've tried using the solutions in this post. Both the property and the surrogate didn't work. The cause would most likely be that protobuf-net doesn't work on dictionary directly but serializes the types a dictionary contains (and a surrogate on object is impossible).如何在protobuf-net中使用代理/填充属性反序列化带有对象值的通用字典?

我的测试代码

class Program 
{ 
    static void Main(string[] args) 
    { 
     var library = new Library(); 
     library.Keeper.Add("Harry Potter", "blablabla text... text..."); 
     library.Keeper.Add("Other book", "Awesome story."); 

     // Write and read to test serializing. 
     Library deserialize; 
     using (var ms = new MemoryStream()) 
     { 
      Serializer.Serialize(ms, library); 

      ms.Flush(); 
      ms.Position = 0; 

      deserialize = Serializer.Deserialize<Library>(ms); 
     } 

     Console.WriteLine(deserialize.Keeper.Count); 
    } 
} 

图书馆类

[ProtoContract] 
public class Library 
{ 
    public Dictionary<string, object> Keeper { get; set; } 

    [ProtoMember(1)] 
    public Dictionary<string, string> KeeperSer 
    { 
     get 
     { 
      var res = new Dictionary<string, string>(); 
      foreach (var pair in Keeper) 
      { 
       res.Add(pair.Key, TypeDescriptor.GetConverter(pair.Value.GetType()).ConvertToInvariantString(pair.Value)); 
      } 
      return res; 
     } 
     set 
     { 
      var set = new Dictionary<string, object>(); 
      foreach (var pair in value) 
      { 
       set.Add(pair.Key, pair.Value); 
      } 
      Keeper = set; 
     } 
    } 

    public Library() 
    { 
     Keeper = new Dictionary<string, object>(); 
    } 
} 

我也尝试添加[ProtoIgnore]到Keeper财产。在运行项目时,在设置者KeeperSerKeeper处添加断点不会触发。获取者确实工作,数据正在由protobuf-net写入MemoryStream。将新项目添加到Library时,长度也会有所不同。

Dictionary<string, object>的原因是我在另一个项目中使用了TypeDescriptor.GetConverter(Type)。我想动态地将类型转换为我需要的类型。

我错过了什么让代理/垫片属性KeeperSer工作?

回答

0

通过测试,似乎任何IEnumerable<object>兼容类型不会以任何方式与Protobuf网工作,因为它根本不知道如何处理它。即使没有错误发生,这些类型的setter也不会被调用。除此之外,使用通用代理来'欺骗'implicit operator在Protobuf-net内给出了一个递归循环。现在,我想我只需要存储对象数据的文本表示(Dictionary<string,string>),并且从不使用Dictionary<string,object>与Protobuf-net串行器一起使用。

相关问题