简体   繁体   English

从自动实现的属性切换时,如何保持可序列化的类向后兼容

[英]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.

相关问题 如何访问自动实现的属性的支持变量? - How can I access the backing variable of an auto-implemented property? 如何在使用自动实现的属性时将字符串初始化为“” - How to initialize a string to “” when using auto-implemented property 如何在C#中的类中创建自动实现的列表属性? - How do I create an auto-implemented list property in a class in C#? 我可以为 C# 自动实现的属性(也称为自动支持字段)定义自定义 getter 吗? - Can I define a custom getter for a C# auto-implemented property (a.k.a. auto backing field)? 使用Roslyn将自动实现的属性添加到类 - Adding Auto-Implemented Property to class using Roslyn 自动实现属性的继承,派生类中仅需要getter - Inheritance of auto-implemented property with only getter needed in a derived class 如何确定一个属性是否是带有反射的自动实现的属性? - How to find out if a property is an auto-implemented property with reflection? 在C#中,我可以为自动实现的属性访问器创建委托实例吗? - In C# can I create a delegate instance to an auto-implemented property accessor? 可以仅在自动实现的属性的Setter上设置属性吗? - Can an Attribute be set only on the Setter of an Auto-Implemented Property? 如何在VS类设计器中创建自动实现的属性 - How do I create auto-implemented properties in the VS class designer
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM