Ignore inherited class when serializing object

后端 未结 4 1469
不思量自难忘°
不思量自难忘° 2021-01-24 21:29

When I inherit from a class and serialize the new class I get all all properties. How can I prevent that? I have no control over the class that I inherit from. So I can\'t add

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-24 22:11

    Late to the party, but: I just stumbled over your question because I have similar problem. I inherit from a class, but the logic of my derived class renders some properties of the base class redundant or obsolete for serialization, and so I don't want to serialize them.

    I found a solution which isn't as automatic as yours but more flexible: Override the base class properties and mark them with [XmlIgnore]. The implementation in the override can just consist of a call to the base implementation; the only purpose of the overriding is to attach the XmlIgnore attribute to it.

    It's less automatic because if properties in the base class change you have to reflect the changes in the derived class. That's on the other hand more flexible because you can select which properties to ignore.

    Admittedly this solution doesn't scale well and is best suited for smaller projects with close ties between the involved classes and people.

提交回复
热议问题