[英]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. 我需要更改MyProperty,以使其不再自动实现。 My question is, will this break compatibility?
我的问题是,这会破坏兼容性吗? In other words, will MyClass instances serialized before this change be correctly deserialized after this change?
换句话说,在此更改之前序列化的MyClass实例是否可以在此更改之后正确地反序列化? 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. 这样,您可以使用
base.MyProperty
访问自动命名的后备字段。 You can have a new field in the derived class that is used preferably. 您可以在派生类中有一个新字段,最好使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.