我想序列化XML序列化一个复杂类型(类),它有一个System.Drawing.Bitmap类型的属性。
/// <summary>
/// Gets or sets the large icon, a 32x32 pixel image representing this face.
/// </summary>
/// <value>The large icon.</value>
public Bitmap LargeIcon { get; set; }
我现在发现,使用默认的XML序列化程序序列化Bitmap是不起作用的,因为它没有公共的无参数构造函数,这是默认xml序列化程序所必需的。
我知道以下几点:
上还有一个深度序列化项目
我不想引用另一个项目,也不想对我的类进行广泛的调整,只允许对这些位图进行xml序列化。
有没有办法让它变得简单?
非常感谢,马塞尔
发布于 2009-12-15 20:39:01
我会这样做:
[XmlIgnore]
public Bitmap LargeIcon { get; set; }
[Browsable(false),EditorBrowsable(EditorBrowsableState.Never)]
[XmlElement("LargeIcon")]
public byte[] LargeIconSerialized
{
get { // serialize
if (LargeIcon == null) return null;
using (MemoryStream ms = new MemoryStream()) {
LargeIcon.Save(ms, ImageFormat.Bmp);
return ms.ToArray();
}
}
set { // deserialize
if (value == null) {
LargeIcon = null;
} else {
using (MemoryStream ms = new MemoryStream(value)) {
LargeIcon = new Bitmap(ms);
}
}
}
}
发布于 2009-12-15 20:29:04
BitMap类并没有被设计成可以很容易地序列化。所以,不,没有简单的方法来纠正设计决策。
发布于 2009-12-15 20:39:13
实现IXmlSerializable
,然后自己处理所有的序列化细节。
既然你说它是一个大字体,而你只对位图有一个问题,那么考虑这样做:
public class BitmapContainer : IXmlSerializable
{
public BitmapContainer() { }
public Bitmap Data { get; set; }
public XmlSchema GetSchema()
{
throw new NotImplementedException();
}
public void ReadXml(XmlReader reader)
{
throw new NotImplementedException();
}
public void WriteXml(XmlWriter writer)
{
throw new NotImplementedException();
}
}
public class TypeWithBitmap
{
public BitmapContainer MyImage { get; set; }
public string Name { get; set; }
}
https://stackoverflow.com/questions/1907077
复制相似问题