How to Ignore Non-Serializable Child When Serializing Object?

  • Thread starter Thread starter O.B.
  • Start date Start date
O

O.B.

I have two classes, Logger and LoggerRuntime. Logger is serializble,
LoggerRuntime is not. LoggerRuntime inherits from Logger. At runtime,
I get a list of LoggerRuntime instances to save to an XML file. I only
want the public attributes of the parent Logger class to get written to
the file. Therefore, I cast the LoggerRuntime objects to "Logger" and
then try to serialize the Logger objects. Instead, I get the following
error:

System.InvalidOperationException: The type
SerializationTest.LoggerRuntime was not expected. Use the XmlInclude or
SoapInclude attribute to specify types that are not known statically.

What am I doing wrong?
 
Casting doesn't matter; it still *is* a LoggerRuntime, no matter how it is
masquerading. In this case, you would probably be best to tell XmlSerializer
to expect also LoggerRuntime (there is an overload for this, or you can use
the XmlInclude attribute on Logger) - and mark the additional public
properties (in LoggerRuntime) with [XmlIgnore] to stop it from attempting to
serialize them.

Marc
 
Back
Top