gpt4 book ai didi

c# - Dictionary 上 .NET 二进制序列化的奇怪行为

转载 作者:可可西里 更新时间:2023-11-01 03:08:21 24 4
gpt4 key购买 nike

我在 .NET 的二进制序列化中遇到了一个奇怪的行为,至少符合我的预期。

OnDeserialization 回调之后,加载的 Dictionary 的所有项目都被添加到它们的父级。相比之下,List 则采用另一种方式。这在现实世界的存储库代码中可能真的很烦人,例如,当您需要向字典项添加一些委托(delegate)时。请检查示例代码并观察断言。

这是正常行为吗?

[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");
}
}

最佳答案

是的,您在 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);
}

关于c# - Dictionary<Key, Value> 上 .NET 二进制序列化的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/457134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com