本文介绍了过时的属性导致属性被 XmlSerialization 忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构一些序列化为 XML 的对象,但需要保留一些属性以实现向后兼容性,我有一种方法可以将旧对象转换为新对象,并将过时的属性清空.我想使用 Obsolete 属性告诉其他开发人员不要使用此属性,但这会导致 XmlSerializer 忽略该属性.

I'm refactoring some objects that are serialized to XML but need to keep a few properties for backwards compatibility, I've got a method that converts the old object into the new one for me and nulls the obsolete property. I want to use the Obsolete attribute to tell other developers not to use this property but it is causing the property to be ignored by the XmlSerializer.

类似代码:

[Serializable]
public class MySerializableObject
{
    private MyObject _oldObject;
    private MyObject _anotherOldObject;

    private MyObject _newBetterObject;

    [Obsolete("Use new properties in NewBetterObject to prevent duplication")]
    public MyObject OldObject
    {
      get { return _oldObject; }
      set { _oldObject = value; }
    }

    [Obsolete("Use new properties in NewBetterObject to prevent duplication")]
    public MyObject AnotherOldObject
    {
      get { return _anotherOldObject; }
      set { _anotherOldObject = value; }
    }

    public MyObject NewBetterObject
    {
      get { return _anotherOldObject; }
      set { _anotherOldObject = value; }
    }
}

关于解决方法的任何想法?我最好的解决方案是在 XML 注释中写过时...

Any ideas on a workaround? My best solution is to write obsolete in the XML comments...

更新:我使用的是 .NET 2.0

推荐答案

编辑:阅读 MS Connect 文章后,.Net 2.0 似乎有一个功能",它使 ObsoleteAttribute 等同于 XmlIgnoreAttribute 而文档中没有任何通知.所以我要修改我的答案,说在这种情况下,吃蛋糕和吃蛋糕的唯一方法是遵循@Will 的建议和 手动实现序列化.这将是您在 XML 中包含 Obsolete 属性的唯一未来证明方式.它在 .Net 2.0 中并不漂亮,但 .Net 3.0+ 可以让生活更轻松.

EDIT: After reading a MS Connect article, it appears that .Net 2.0 has a 'feature' where it makes ObsoleteAttribute equivalent to XmlIgnoreAttribute without any notification in the documentation. So I'm going to revise my answer to say that the only way to have your cake and eat it too in this instance is to follow @Will's advice and implement serialization manually. This will be your only future proof way of including Obsolete properties in your XML. It is not pretty in .Net 2.0, but .Net 3.0+ can make life easier.

来自 XmlSerializer:

标有过时属性的对象不再序列化在 .NET Framework 3.5 中,XmlSerializer 类不再序列化标记为 [Obsolete] 的对象.

这篇关于过时的属性导致属性被 XmlSerialization 忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 05:54