Object XmlSerialization with protected property setters

拥有回忆 提交于 2020-01-01 04:49:05

问题


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?


回答1:


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)



回答2:


Even though it doesn't directly answer your question, note that you can serialize properties with an internal setter. To do that, you need to pre-generate the XML serialization assembly with Sgen.exe, and declare that assembly as "friend" using the InternalsVisibleTo attribute :

[assembly:InternalsVisibleTo("MyAssembly.XmlSerializers")]


来源:https://stackoverflow.com/questions/1751448/object-xmlserialization-with-protected-property-setters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!