When implementing IXmlSerializable, how to only override either ReadXml or WriteXml and not both?

后端 未结 2 491
耶瑟儿~
耶瑟儿~ 2021-02-01 09:52

I would like to implement IXmlSerializable on a class and only override either ReadXml or WriteXml, but not both. If I didn\'t implement IXMLSerializable on this class, the XML

2条回答
  •  说谎
    说谎 (楼主)
    2021-02-01 10:09

    The ability to perform actions before/after serialisation/deserialisation is provided with attributes. Mark a method with OnDeserializedAttribute for it to be called after an instance has been deserialised, just ensure the method has the right signature:

    [OnDeserializedAttribute()]
    private void RunThisMethod(StreamingContext context) { 
      // ...
    }
    

    NB. This attribute works for Binary, SOAP and DataAttribute formatters, but not for XmlSerializer. There is no attribute or mechanism other than implementing IXmlSerializable.

    Also do not forget that you can read XML documents directly and write code to (de)serialize.


    Original answer: If you need to completely override one of serialisation or deserialisation (and thus implement IXmlSerializable then you have to do both yourself.

    It may be possible to make use of attributes and other mechanisms to avoid using IXmlSerializable, could you expand the question with details of why you need to implement just one of ReadXml or WriteXml.

提交回复
热议问题