I am trying to serialize some properties defined as Pen
in my class. As I want to find the simplest and most elegant way to do that, I've tried to apply the solution described in this answer to the Pen
type. I only need to serialize the Color
, DashStyle
and Width
properties of a Pen
, so I've come up with the following class:
public class XmlPen {
private Pen pen = new Pen(Color.Black, 1.0F);
[XmlAttribute]
public String ColorHtml {
get { return ColorTranslator.ToHtml(this.pen.Color); }
set { this.pen.Color = ColorTranslator.FromHtml(value); }
}
[XmlAttribute]
public DashStyle Style {
get { return this.pen.DashStyle; }
set { this.pen.DashStyle = value; }
}
[XmlAttribute]
public float Width {
get { return this.pen.Width; }
set { this.pen.Width = value; }
}
public XmlPen() {
}
public XmlPen(Pen pen) {
this.pen = pen;
}
public static implicit operator Pen(XmlPen xmlPen) {
return xmlPen.pen;
}
public static implicit operator XmlPen(Pen pen) {
return new XmlPen(pen);
}
}
According to the mentionned answer, I only need to add the following attribute in front of each Pen
property I want to serialize:
[XmlElement(Type = typeof(XmlPen))]
public Pen SomePen { get; set; }
But that doesn't work, I get a InvalidOperationException when trying to serialize my object:
System.Drawing.Pen cannot be serialized because it does not have a parameterless constructor.
My questions are:
- Why am I getting this error? Doesn't the
[XmlElement(Type = typeof(XmlPen))]
suggests that theXmlPen
class should be used when (de)serializing thePen
property? - Is there a trick that would allow me to use this solution on types that do not have a parameterless constructor?
PS: I am not interested in wrapping the Pen
class in another one if I have to reference this new class everywhere in my code, nor am I interested to add a hidden property in my class to be used when (de)serializing.