将 C#/.NET 中的位图序列化为 XML
我想要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 序列化程序则强制使用该构造函数。
我知道以下内容:
- 存在一种解决方法,发布在这里: http://www.dotnetspider.com/resources/4759-XML-Serialization-C-Part-II-Images.aspx 。然而,由于这包括添加另一个属性,这在我看来有点像黑客。
- sourceforge 上还有一个深度 XML 序列化项目。
我不想引用另一个项目,也不想广泛调整我的类以仅允许这些位图的 xml 序列化。
有没有办法保持这么简单?
非常感谢,Marcel
I want to XML-Serialize a complex type (class), that has a property of type System.Drawing.Bitmap among others.
/// <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; }
I now have found out that serializing the Bitmap with the default XML serializer does not work, because it does not have a public parameterless constructor, which is mandatory with the default xml serializer.
I am aware of the following:
- There exists a workaround, posted here: http://www.dotnetspider.com/resources/4759-XML-Serialization-C-Part-II-Images.aspx
. However since this includes adding another property this seems to me a bit of a hack. - There is also a deep XML serializing project on sourceforge.
I rather would not like referencing another project nor extensively tweak my class to just allow xml serialization of those bitmaps.
Is there no way to keep that simple?
Many thanks, Marcel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会做类似的事情:
I would do something like:
您还可以实现ISerialized
并使用SerializationInfo
手动处理位图内容。编辑: João 是正确:处理 XML 序列化的正确方法是实现
IXmlSerialized
,而不是ISerialized
:You can also to implementISerializable
and to useSerializationInfo
to deal manually with your bitmap content.EDIT: João is right: Correct way to deal with XML serialization is to implement
IXmlSerializable
, notISerializable
:BitMap 类并未设计为易于 XML 序列化。所以,不,没有简单的方法来纠正设计决策。
The BitMap class has not been designed to be easily XML Serialized. So, no, there's not simple way to correct a design decision.
实现
IXmlSerialized
,然后自己处理所有序列化详细信息。既然你说它是一个大类型,并且你只有位图问题,请考虑执行以下操作:
Implement
IXmlSerializable
and then handle all the serialization details yourself.Since you say it's a large type and you only have a problem with the bitmap consider doing something like this: