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
财产。在运行项目时,在设置者KeeperSer
或Keeper
处添加断点不会触发。获取者确实工作,数据正在由protobuf-net写入MemoryStream
。将新项目添加到Library
时,长度也会有所不同。
Dictionary<string, object>
的原因是我在另一个项目中使用了TypeDescriptor.GetConverter(Type)
。我想动态地将类型转换为我需要的类型。
我错过了什么让代理/垫片属性KeeperSer
工作?