我在.NET的二进制序列化中遇到了奇怪的行为,至少在我的预期中是这样。
在OnDeserialization
回调之后,加载的Dictionary
的所有项都会添加到其父对象中。相比之下,List
采用了另一种方式。在现实世界的存储库代码中,这可能真的很烦人,例如当您需要向字典项添加一些委托时。请检查示例代码并查看断言。
这是正常行为吗?
[Serializable]
public class Data : IDeserializationCallback
{
public List<string> List { get; set; }
public Dictionary<string, string> Dictionary { get; set; }
public Data()
{
Dictionary = new Dictionary<string, string> { { "hello", "hello" }, { "CU", "CU" } };
List = new List<string> { "hello", "CU" };
}
public static Data Load(string filename)
{
using (Stream stream = File.OpenRead(filename))
{
Data result = (Data)new BinaryFormatter().Deserialize(stream);
TestsLengthsOfDataStructures(result);
return result;
}
}
public void Save(string fileName)
{
using (Stream stream = File.Create(fileName))
{
new BinaryFormatter().Serialize(stream, this);
}
}
public void OnDeserialization(object sender)
{
TestsLengthsOfDataStructures(this);
}
private static void TestsLengthsOfDataStructures(Data data)
{
Debug.Assert(data.List.Count == 2, "List");
Debug.Assert(data.Dictionary.Count == 2, "Dictionary");
}
}
发布于 2009-01-19 10:42:37
我可以重现这个问题。我在谷歌周围看了看,发现了这个:http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94265虽然我不确定它是不是完全相同的问题,但它看起来很相似。
编辑:
我认为添加这段代码可能已经解决了这个问题?
public void OnDeserialization(object sender)
{
this.Dictionary.OnDeserialization(sender);
}
没有时间进行详尽的测试,我想先于Marc找到答案;-)
发布于 2009-01-19 10:43:31
是的,您已经在Dictionary<TKey, TValue>
反序列化中发现了一个恼人的怪癖。您可以通过手动调用字典的OnDeserialization()
方法来绕过它:
public void OnDeserialization(object sender)
{
Dictionary.OnDeserialization(this);
TestsLengthsOfDataStructures(this);
}
顺便说一句,您还可以使用[OnDeserialized]
属性而不是IDeserializationCallback
[OnDeserialized]
public void OnDeserialization(StreamingContext context)
{
Dictionary.OnDeserialization(this);
TestsLengthsOfDataStructures(this);
}
发布于 2009-01-19 10:42:18
有趣的是。对于信息,我尝试了基于属性的方法(如下),它的行为是相同的……非常好奇!我无法解释-我只是回复确认复制,并提到[OnDeserialized]
的行为:
[OnDeserialized] // note still not added yet...
private void OnDeserialized(StreamingContext context) {...}
编辑-找到"connect“问题here。尝试添加到您的回调:
Dictionary.OnDeserialization(this);
https://stackoverflow.com/questions/457134
复制相似问题