Difference of attributes in properties of inherited classes
I have two classes: Element
and Display
.
Now both classes have a lot of properties in common, so I consider inheritance from the base class.
Now there is a problem. For serialization, the class Element
must have [XmlIgnore]
before each of these properties, but the class Display
not.
How can I handle this?
Old:
public class Element
{
[Browsable(false)]
[XmlIgnore]
public Brush BackgroundBrush { get; set }
}
public class Display
{
public Brush BackgroundBrush { get; set }
}
New:
public class DispBase
{
public Brush BackgroundBrush { get; set; }
}
public class Element : DispBase
{
// what to write here, to achieve XmlIgnore and Browsable(false)?
}
public class Display : DispBase
{
}
+3
source to share
2 answers
You can make the base class and properties abstract and set attributes for the derived class where needed:
public abstract class DispBase
{
public abstract Brush BackgroundBrush { get; set; }
}
public class Element : DispBase
{
[XmlIgnore]
[Browsable(false)]
public override Brush BackgroundBrush { get; set; }
}
public class Display : DispBase
{
public override Brush BackgroundBrush { get; set; }
}
+5
source to share
You can use the XmlAttributes class and set the XmlIgnore dynamically.
Examples of classes:
public class Brush { }
public class DispBase
{
public Brush BackgroundBrush { get; set; }
}
public class Element : DispBase { }
public class Display : DispBase { }
Sample code:
var element = new Element { BackgroundBrush = new Brush() };
var display = new Display { BackgroundBrush = new Brush() };
using (var fs = new FileStream("test1.txt", FileMode.Create))
{
var attributes = new XmlAttributes { XmlIgnore = true };
var overrides = new XmlAttributeOverrides();
overrides.Add(typeof(DispBase), "BackgroundBrush", attributes);
var ser = new XmlSerializer(typeof(Element), overrides);
ser.Serialize(fs, element);
}
using (var fs = new FileStream("test2.txt", FileMode.Create))
{
var ser = new XmlSerializer(typeof(Display));
ser.Serialize(fs, display);
}
+1
source to share