具有受保护属性设置器的对象 XmlSerialization [英] Object XmlSerialization with protected property setters

查看:20
本文介绍了具有受保护属性设置器的对象 XmlSerialization的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的对象

<预><代码>[可序列化()]公共类 PersistentObject{公共虚拟 int ID {得到 { 返回 ID;}受保护的集合 { id = value;}}...}

当我尝试将其序列化为 xml 时,出现错误无法在此上下文中使用属性或索引器 PersistentObject.ID,因为设置访问器不可访问".如果 setter 不存在,则它可以正常工作.我想将此 ID 保持为序列化,而无需涉及 ID 上的 [XmlIgnore()] 的 hacktastic 解决方案.如果我可以在 setter 上添加 [XmlIgnore()],我更愿意,但编译器会抱怨.有人有一个好的解决方案吗?

解决方案

很遗憾,没有.XmlSerializer 有一些令人恼火的东西.这是其中之一.选项:

  • 使用DataContractSerializer(支持protected等,但提供完整的xml控制)
  • [XmlIgnore] 注释 - 没什么问题
  • 实现 IXmlSerializable - 努力工作,很容易出错
  • 去掉setter,有一个separate protected 方法来设置值
  • 使用 XmlSerializer 构造函数,让您在运行时指定所有内容;大量工作/维护,您需要手动缓存序列化程序(否则它会创建大量动态程序集)

Here is my object


    [Serializable()]
    public class PersistentObject
    {
        public virtual int ID {
            get { return id; }
            protected set { id = value;}
        }
        ...
     }

When I try to serialize this to xml, I get an error "The Property or indexer PersistentObject.ID cannot be used in this context because the set accessor is inaccessible" . If the setter doesn't exist, it works fine. I want to keep this ID as serialized without a hacktastic solution that involves an of [XmlIgnore()] on ID. I would prefer if I could add [XmlIgnore()] on just the setter, but the compiler complains. Anybody have a good solution around this?

解决方案

Unfortunately, no. XmlSerializer has some things that are... irritating. This is one of them. Options:

  • use DataContractSerializer (which supports protected etc, but doesn't offer full xml control)
  • annotate with [XmlIgnore] - nothing wrong with it
  • implement IXmlSerializable - hard work and very easy to get wrong
  • take off the setter, and have a separate protected method to set the value
  • use the XmlSerializer constructor that lets you specify everything at runtime; lots of work/maintenance, and you need to manually cache the serializer (otherwise it creates lots of dynamic assemblies)

这篇关于具有受保护属性设置器的对象 XmlSerialization的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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