【问题标题】:Strange behaviour of .NET binary serialization on Dictionary<Key, Value>Dictionary<Key, Value> 上 .NET 二进制序列化的奇怪行为
【发布时间】: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


【解决方案1】:

是的,您在Dictionary&lt;TKey, TValue&gt; 反序列化中发现了一个恼人的怪癖。您可以通过手动调用字典的OnDeserialization() 方法来绕过它:

public void OnDeserialization(object sender)
{
    Dictionary.OnDeserialization(this);
    TestsLengthsOfDataStructures(this);
}

顺便说一句,您也可以使用[OnDeserialized] 属性而不是IDeserializationCallback

[OnDeserialized]
public void OnDeserialization(StreamingContext context)
{
    Dictionary.OnDeserialization(this);
    TestsLengthsOfDataStructures(this);
}

【讨论】:

  • 只是添加一个警告:在我的环境中,在调用其OnDeserialization 之前尝试添加到反序列化字典会导致从字典中生成NullReferenceException
【解决方案2】:

我可以重现该问题。环顾谷歌,发现:http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94265 虽然我不确定这是完全相同的问题,但看起来非常相似。

编辑:

我认为添加此代码可能会解决问题?

    public void OnDeserialization(object sender)
    {
            this.Dictionary.OnDeserialization(sender);
    }

没有时间进行详尽的测试,我想击败 Marc 得到答案 ;-)

【讨论】:

  • 我想我们几乎是在同一时间找到了它——也许你抢了我,所以 +1 给你 ;-p
【解决方案3】:

有趣...对于信息,我尝试使用基于属性的方法(如下),它的行为相同...非常好奇!我无法解释 - 我只是回复确认转载,并提及 [OnDeserialized] 行为:

[OnDeserialized] // note still not added yet...
private void OnDeserialized(StreamingContext context) {...}

编辑 - 发现“连接”问题 here。尝试添加到您的回调中:

Dictionary.OnDeserialization(this);

【讨论】:

  • 只是为了让您知道链接已经失效
猜你喜欢
  • 1970-01-01
  • 2012-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多