如何覆盖C#中的反序列化 [英] How can I override deserialization in C#

查看:90
本文介绍了如何覆盖C#中的反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个课程,随着时间的流逝,它将经历某些版本的更改. 在启动应用程序时,此类内部的数据将被序列化和反序列化.我遇到的问题是,如果我通过添加更多属性来更新类,然后启动应用程序,则旧数据将无法正确加载.
我想做的是覆盖反序列化步骤,我不介意从xml手动重建对象,因为我存储了版本号,并且可以使用它来递归更新对象的版本.

I've got a class that will undergo certain version changes over the course of time. The data from inside this class is serialized and deserialized as part of the startup of my application. The problem I have is if I update the class by adding more properties, and then start the application, the old data does not get loaded properly.
What I'm looking to do is override the deserialization step, I don't mind manually reconstructing the object from xml, as I have a version number stored and can use it to recursively update versions of the object.

有没有可以实现的接口或可以在某处设置的属性?

Is there an interface I can implement, or an attribute I can set somewhere, to be able to do this?

如果您无法想到一种方法来做我想做的事,还有其他选择吗?例如默认属性值,这些属性在我正在加载的xml版本中可能不存在.

If you can't think of a way to do what I want, are there alternatives? such as defaulting values for properties that may not exist in the version of the xml I am loading.

推荐答案

通常,对于版本控制,可以将OptionalField属性用于可能会导致兼容性问题的新添加的成员.在序列化过程中,如果未序列化成员,则将成员值保留为null而不是引发异常.

Typically for versioning, you can use the OptionalField attribute to newly added members that might cause compatibility problems. During serialization, if member was not serialized, this leaves members value as null rather than throwing the exception.

此外,请查看IDeserializationCallback.OnDeserialization界面,该界面可让您自定义反序列化.

Also, take a look at IDeserializationCallback.OnDeserialization interface which allows you to customize your deserialization.

这篇关于如何覆盖C#中的反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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