Lets say we have a derivided class “SerializableLabel” from the base class “System.Windows.Controls.
[XmlRoot("SerializableLabel")]
public class SerializableLabel : Label
{
public string foo = "bar";
}
I’d like to serialize this class but ignore ALL of the properties in the parent class. Ideally the xml would look something like:
<SerializableLable>
<foo>bar</foo>
</SerializableLable>
How is this best achieved?
My first attempt used the typical XmlSerializer approach:
XmlSerializer s = new XmlSerializer(typeof(SerializableLabel));
TextWriter w = new StreamWriter("test.xml");
s.Serialize(w, lbl);
w.Close();
But this raises an exception because the serializer attempts to serialize a base class property which is an interface (ICommand Command).
One possible root of the above problems (including the one pointed out by JP) is that your class hierarchy tries to violate the Liskov Substitution Principle. In simpler terms, the derived class tries not to do what the base class already does. In still other words, you’re trying to create a derived label that is not substitutable for the base label.
The most effective remedy here may involve decoupling the two things that SerializableLabel is tries to do, (a) UI-related functions and (b) storing serializable data, and having them in different classes.