【发布时间】:2010-10-02 05:03:11
【问题描述】:
我在 .NET 的二进制序列化中遇到了一个奇怪的行为,至少在我的预期中。
Dictionary 的所有加载项都在OnDeserialization 回调之后添加到它们的父项。相比之下,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");
}
}
【问题讨论】:
-
我发现很难理解答案,因为您的对象实例与类同名!如何区分静态方法和成员方法?
标签: c# .net serialization dictionary binary