我正在尝试序列化我班级中定义为Pen
的一些属性。由于我想找到最简单,最优雅的方法,我尝试将this answer中描述的解决方案应用于Pen
类型。我只需要序列化Color
的{{1}},DashStyle
和Width
属性,以便我提出以下类:
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无法序列化,因为它没有无参数构造函数。
我的问题是:
[XmlElement(Type = typeof(XmlPen))]
public Pen SomePen { get; set; }
是否建议在(de)序列化[XmlElement(Type = typeof(XmlPen))]
属性时应使用XmlPen
类? PS:如果我必须在我的代码中到处引用这个新类,我不想将Pen
类包装在另一个类中,我也不想在我的类中添加隐藏属性以便在(反)序列
答案 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对象