简体   繁体   中英

How can I keep a serializable class backwards compatible when switching away from an auto-implemented property

I have a class like this:

[Serializable]
public class MyClass
{
    public Dictionary<string, int> MyProperty { get; set; }
}

I need to change MyProperty so that it is no longer auto-implemented. My question is, will this break compatibility? In other words, will MyClass instances serialized before this change be correctly deserialized after this change? Do I have to do anything to guarantee this? What rules govern how this works?

For reference, I want something like:

[Serializable]
public class MyClass
{
    private Dictionary<string, int> _myProperty;
    public Dictionary<string, int> MyProperty
    {
        get { return this._myProperty; }
        set { Validate(value); this._myProperty = value; }
    }
}

EDIT: I tried this specific toy example and it seems to work, but that doesn't give me much confidence because my real example(s) are more complex. I'd like to understand the underlying rules so that I can make an educated guess before testing.

You can use custom deserialization to pull out the field's value by its old name.

Or, make this auto property virtual and derive a class from it. That way you can use base.MyProperty to access the auto-named backing field. You can have a new field in the derived class that is used preferably.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM