問題描述
我在 .NET 的二進制序列化中遇到了一個奇怪的行為,至少在我的預期中.
I encountered a, at least to my expectations, strange behavior in the binary serialization of .NET.
Dictionary
的所有項目在 OnDeserialization
回調之后被添加到它們的父項.相比之下,List
則相反.這在現實世界的存儲庫代碼中可能真的很煩人,例如當您需要向字典項添加一些委托時.請檢查示例代碼并觀察斷言.
All items of a Dictionary
that are loaded are added to their parent AFTER the OnDeserialization
callback. In contrast List
does the other way. This can be really annoying in real world repository code, for example when you need to add some delegates to dictionary items. Please check the example code and watch the asserts.
這是正常行為嗎?
[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");
}
}
推薦答案
我可以重現問題.環顧谷歌,發現:http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94265 雖然我不確定這是完全相同的問題,但看起來非常相似.
I can reproduce the problem. Had a look around Google and found this: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94265 although I'm not sure it's the exact same problem, it seems pretty similar.
我認為添加此代碼可能會解決問題?
I think that adding this code may have fixed the problem?
public void OnDeserialization(object sender)
{
this.Dictionary.OnDeserialization(sender);
}
沒有時間進行詳盡的測試,我想擊敗 Marc 得到答案 ;-)
No time to exhaustively test, and I want to beat Marc to the answer ;-)
這篇關于Dictionary<Key, Value> 上 .NET 二進制序列化的奇怪行為的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!