首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Dictionary<Key、Value>上.NET二进制序列化的奇怪行为

Dictionary<Key、Value>上.NET二进制序列化的奇怪行为
EN

Stack Overflow用户
提问于 2009-01-19 10:15:21
回答 3查看 5.6K关注 0票数 17

我在.NET的二进制序列化中遇到了奇怪的行为,至少在我的预期中是这样。

OnDeserialization回调之后,加载的Dictionary的所有项都会添加到其父对象中。相比之下,List采用了另一种方式。在现实世界的存储库代码中,这可能真的很烦人,例如当您需要向字典项添加一些委托时。请检查示例代码并查看断言。

这是正常行为吗?

代码语言:javascript
复制
[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");
    }
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/457134

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档