Font序列化和反序列化

Font中的Properties都是readonly,并且Font不能被继承,所以序列化和反序列化Font会相对麻烦一点。

需要写一个FontSerializer类来实现Font序列化和反序列化。先写测试代码:

[TestMethod()]
public void FontSerializationTest()
{
    const string _anyFileName = @"D:/FontSerializerTest.xml";
 
    XmlTextWriter writer = new XmlTextWriter(_anyFileName, null);
    writer.Formatting = Formatting.Indented;
    string name = "Font";
    Font font = new Font("Arial", 9, FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout | FontStyle.Underline);;
    FontSerializer.WriteXml(writer, name, font);
    writer.Close();
    font.Dispose();
 
    XmlTextReader reader = new XmlTextReader(_anyFileName);
    font = FontSerializer.ReadXml(reader, name);
    reader.Close();
    Assert.AreEqual(font.Name, _anyFont.Name);
    Assert.AreEqual(font.Size, _anyFont.Size);
    Assert.AreEqual(font.Style, _anyFont.Style);
    font.Dispose();
}

再写实现代码。

using System.Drawing;
using System.Globalization;
using System.Xml;
 
namespace CommonLib
{
    public static class FontSerializer
    {
        #region Methods
 
        public static Font ReadXml(XmlReader reader, string name)
        {
            reader.ReadToFollowing(name);
            reader.ReadStartElement();
            string familyName = reader.ReadElementString("Name");
            float size = float.Parse(reader.ReadElementString("Size"), CultureInfo.InvariantCulture);
            bool bold = bool.Parse(reader.ReadElementString("Bold"));
            bool italic = bool.Parse(reader.ReadElementString("Italic"));
            bool strikeout = bool.Parse(reader.ReadElementString("Strikeout"));
            bool underline = bool.Parse(reader.ReadElementString("Underline"));
            reader.ReadEndElement();
 
            FontStyle fontStyle = FontStyle.Regular;
            if (bold) fontStyle |= FontStyle.Bold;
            if (italic) fontStyle |= FontStyle.Italic;
            if (strikeout) fontStyle |= FontStyle.Strikeout;
            if (underline) fontStyle |= FontStyle.Underline;
            Font font = new Font(familyName, size, fontStyle);
            return font;
        }
 
        public static void WriteXml(XmlWriter writer, string name, Font font)
        {
            writer.WriteStartElement(name);
            writer.WriteElementString("Name", font.Name);
            writer.WriteElementString("Size", font.Size.ToString(CultureInfo.InvariantCulture));
            writer.WriteElementString("Bold", font.Bold.ToString());
            writer.WriteElementString("Italic", font.Italic.ToString());
            writer.WriteElementString("Strikeout", font.Strikeout.ToString());
            writer.WriteElementString("Underline ", font.Underline.ToString());
            writer.WriteEndElement();
        }
 
        #endregion
    }
}

见人用过Stream和BinaryFormatter序列化和反序列化Font,但不能在XML文件中任意节点序列化Font。以上实现可以解决这个问题。

posted @   wanghui  阅读(1285)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示