鉴于以下课程,
public static void Test()
{
var bigDictionary = new Dictionary<string, TestClass>();
bigDictionary.Add("entry1", new TestClass());
bigDictionary.Add("entry2", new TestClass());
bigDictionary.Add("entry3", new TestClass());
// EDIT: Added these lines
bigDictionary["entry1"].MyDictionary.Add(1, new SecondTestClass() { MyVar = "hello" });
bigDictionary["entry1"].MyDictionary.Add(2, new SecondTestClass() { MyVar = "world" });
bigDictionary["entry2"].MyDictionary.Add(1, new SecondTestClass() { MyVar = "please" });
bigDictionary["entry2"].MyDictionary.Add(2, new SecondTestClass() { MyVar = "work" });
using (var file = System.IO.File.Create("test.temp"))
{
ProtoBuf.Serializer.Serialize(file, bigDictionary);
}
Dictionary<string, TestClass> outDict = null;
using (var file = System.IO.File.OpenRead("test.temp"))
{
outDict = ProtoBuf.Serializer.Deserialize<Dictionary<string, TestClass>>(file);
}
// EDIT: You'll notice these asserts fail
System.Diagnostics.Debug.Assert(outDict["entry1"].MyDictionary.ContainsKey(1));
System.Diagnostics.Debug.Assert(outDict["entry1"].MyDictionary.ContainsKey(2));
System.Diagnostics.Debug.Assert(outDict["entry2"].MyDictionary.ContainsKey(1));
System.Diagnostics.Debug.Assert(outDict["entry2"].MyDictionary.ContainsKey(2));
}
[System.Runtime.Serialization.DataContract]
public class TestClass
{
public TestClass()
{
MyDictionary = new Dictionary<int,SecondTestClass>();
}
[System.Runtime.Serialization.DataMember]
public Dictionary<int, SecondTestClass> MyDictionary { get; set; }
}
[System.Runtime.Serialization.DataContract]
public class SecondTestClass
{
[System.Runtime.Serialization.DataMember]
public string MyVar { get; set; }
}
(如何)我可以bigDictionary
序列化而不抛出以下异常?
"Only data-contract classes (and lists/arrays of such) can be processed (error processing Dictionary`2)"
(我尝试使用DataContract / DataMember ProtoContract / ProtoMember等进行标记,但似乎没有任何工作)
提前感谢您的帮助。
编辑:似乎我已经解决了这个问题。鉴于上面编辑的代码,您会注意到断言失败。所以看起来内部字典根本没有被序列化。但是,如果我将DataContract标签更改为Protobuf.ProtoContract(和DataMember到ProtoMember),它会正确地拾取内部字典。我是否误用了库或这是一个错误?
答案 0 :(得分:1)
答案是抛出的异常有点误导,它是字典中对象的序列化错误,而不是字典本身。我正在处理的实际实现比我给出的示例稍微复杂一些,因此有一个类型为object的变量,它正在打破它。
答案 1 :(得分:0)
据我所知,DataContract / DataMember在WCF合同中被大量使用(至少,这就是我所知道的)。您还可以查看[Serializable]属性,这可能更适合您的情况。
干杯,佩里