我在.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 …Run Code Online (Sandbox Code Playgroud)