Strange behaviour of .NET binary serialization on Dictionary

前端 未结 3 1371
北恋
北恋 2020-12-25 08:29

I encountered a, at least to my expectations, strange behavior in the binary serialization of .NET.

All items of a Dictionary that are loaded are added

相关标签:
3条回答
  • 2020-12-25 08:37

    Interesting... for info, I tried it with the attribute-based approach (below), and it behaves the same... very curious! I can't explain it - I'm just replying to confirm reproduced, and to mention the [OnDeserialized] behaviour:

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

    Edit - found "connect" issue here. Try adding to your callback:

    Dictionary.OnDeserialization(this);
    
    0 讨论(0)
  • 2020-12-25 08:45

    I can reproduce the problem. Had a look around Google and found this: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94265 although I'm not sure it's the exact same problem, it seems pretty similar.

    EDIT:

    I think that adding this code may have fixed the problem?

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

    No time to exhaustively test, and I want to beat Marc to the answer ;-)

    0 讨论(0)
  • 2020-12-25 08:55

    Yes, you've discovered an annoying quirk in Dictionary<TKey, TValue> deserialization. You can get around it by manually calling the dictionary's OnDeserialization() method:

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

    Incidentally, you can also use the [OnDeserialized] attribute rather than IDeserializationCallback:

    [OnDeserialized]
    public void OnDeserialization(StreamingContext context)
    {
        Dictionary.OnDeserialization(this);
        TestsLengthsOfDataStructures(this);
    }
    
    0 讨论(0)
提交回复
热议问题