如何使用XmlElementAttribute.Type属性序列化Pen

时间:2014-10-14 12:05:35

标签: c# xml serialization

我正在尝试序列化我班级中定义为Pen的一些属性。由于我想找到最简单,最优雅的方法,我尝试将this answer中描述的解决方案应用于Pen类型。我只需要序列化Color的{​​{1}},DashStyleWidth属性,以便我提出以下类:

Pen

根据the mentionned answer,我只需要在我要序列化的每个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); } } 属性前面添加以下属性:

Pen

但是这不起作用,我在尝试序列化对象时遇到 InvalidOperationException

  

System.Drawing.Pen无法序列化,因为它没有无参数构造函数。


我的问题是:

  1. 为什么我收到此错误? [XmlElement(Type = typeof(XmlPen))] public Pen SomePen { get; set; } 是否建议在(de)序列化[XmlElement(Type = typeof(XmlPen))]属性时应使用XmlPen类?
  2. 是否有一个技巧可以让我在没有无参数构造函数的类型上使用此解决方案?
  3. PS:如果我必须在我的代码中到处引用这个新类,我不想将Pen类包装在另一个类中,我也不想在我的类中添加隐藏属性以便在(反)序列

1 个答案:

答案 0 :(得分:0)

Why am I getting this error?

因为您的Pen类中没有parameter-less构造函数

Doesn't the [XmlElement(Type = typeof(XmlPen))] suggests that the XmlPen class should be used when (de)serializing the Pen property?

Pen是一个独立的对象,而Deserialization将需要Pen Class中的公共无参数构造函数

修改

评论问题

Isn't the serializer supposed to use the parameterless constructor of the XmlPen class?

否,因为在序列化或反序列化对象时,public static implicit operator XmlPen(Pen pen)仍然需要在运行时需要构造的Pen对象