该类用来序列化一些不支持序列化对象或者简化序列化对象,部分代码来自网上。
public class SerialHelper { #region Serialization Helpers #region Helper classes/structs public struct XmlFont { public string FontFamily; public GraphicsUnit GraphicsUnit; public float Size; public FontStyle Style; public XmlFont(Font f) { FontFamily = f.FontFamily.Name; GraphicsUnit = f.Unit; Size = f.Size; Style = f.Style; } public Font ToFont() { return new Font(FontFamily, Size, Style, GraphicsUnit); } } public struct XmlRect { public int Left, Top, Width, Height; public XmlRect(Rectangle rectangle) { this.Left = rectangle.Left; this.Top = rectangle.Top; this.Width = rectangle.Width; this.Height = rectangle.Height; } public Rectangle ToRectangle() { return new Rectangle(Left, Top, Width, Height); } } #endregion public enum ColorFormat { NamedColor, ARGBColor, } public static XmlRect SerializeRect(Rectangle rectangle) { return new XmlRect(rectangle);//string.Format("{0}:{1}:{2}:{3}", rectangle.Left,rectangle.Top,rectangle.Width,rectangle.Height); } public static Rectangle DeserializeRect(XmlRect xmlRect) { return xmlRect.ToRectangle(); } public static string SerializeColor(Color color) { if (color.IsNamedColor) return string.Format("{0}:{1}", ColorFormat.NamedColor, color.Name); else return string.Format("{0}:{1}:{2}:{3}:{4}", ColorFormat.ARGBColor, color.A, color.R, color.G, color.B); } public static Color DeserializeColor(string color) { byte a, r, g, b; string[] pieces = color.Split(new char[] { ':' }); ColorFormat colorType = (ColorFormat)Enum.Parse(typeof(ColorFormat), pieces[0], true); switch (colorType) { case ColorFormat.NamedColor: return Color.FromName(pieces[1]); case ColorFormat.ARGBColor: a = byte.Parse(pieces[1]); r = byte.Parse(pieces[2]); g = byte.Parse(pieces[3]); b = byte.Parse(pieces[4]); return Color.FromArgb(a, r, g, b); } return Color.Empty; } public static XmlFont SerializeFont(Font font) { return new XmlFont(font); } public static Font DeserializeFont(XmlFont font) { return font.ToFont(); } #endregion }
用法示例
[Browsable(true)] [XmlIgnore()] public Font FontObject { get => textFont; set => textFont = value; } [Browsable(false)] [XmlElement("FontObject")] public SerialHelper.XmlFont XmlFontObject { get { return SerialHelper.SerializeFont(FontObject); } set { FontObject = SerialHelper.DeserializeFont(value); } }
[Browsable(true)] [XmlIgnore()] public Rectangle Rect { get => rect; set => rect = value; } [Browsable(false)] [XmlElement("RectObject")] public SerialHelper.XmlRect XmlRectObject { get { return SerialHelper.SerializeRect(Rect); } set { Rect = SerialHelper.DeserializeRect(value); } }
[Browsable(true)] [XmlIgnore()] public Color BackColor { get => backColor; set => backColor = value; } [Browsable(false)] [XmlElement("BackColorObject")] public string XmlBackColorObject { get { return SerialHelper.SerializeColor(BackColor); } set { BackColor = SerialHelper.DeserializeColor(value); } }