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。以上实现可以解决这个问题。
标签:
C#与dotNet
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?