从对象的较旧版本反序列化对象的较新版本 [英] Deserializing a newer version of an object from an older version of the object

查看:89
本文介绍了从对象的较旧版本反序列化对象的较新版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我上过这堂课:

[Serializable]
public class SomeClass 
{
   public SomeClass() {//init}
   public string SomeString {get;set;}
}

该类在应用程序关闭时被序列化,并在下次运行时反序列化.

This class gets Serialized when the application closes, and gets deserialized on the next run.

然后,我构建它并发布了该应用程序,现在该类已更改:

Then, I built it and released the application, and now the class has changed:

[Serializable]
public class SomeClass
{
   public SomeClass() {//init}
   public string SomeString {get;set;}
   public int SomeInt {get;set;}
}

是否可以在反序列化时将属性设置为默认值,以防在旧的序列化对象中找不到该属性?

Is there a way to set a property to its default on deserialization in case its not found in the old serialized object?

我想到的一种方法是保留类的旧版本,然后检查序列化的版本,然后循环旧对象的属性并将其设置在新对象中,但这对我来说是不合理的,任何其他解决方案有道理吗?

One way I thought about is keeping the old version of the class, then check the version that was serialized then looping properties of the old object and setting them in the new object, but this is non sense to me, any other solution that makes sense?

推荐答案

您可以使用属性标记字段

You can mark fields with the attribute

[OptionalField()]

,如版本耐错序列化

该类将如下所示:

[Serializable()]
public class SomeClass
{
    public SomeClass() {//init}
    public string SomeString { get; set; }

    [OptionalField(VersionAdded = 2)]
    public int SomeInt { get; set; }


    [OnDeserialized()]
    private void SetValuesOnDeserialized(StreamingContext context)
    {
        this.SomeInt = 10;
    }
}

这篇关于从对象的较旧版本反序列化对象的较新版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆