如何XMLSERIALIZE System.Drawing.Font类System、XMLSERIALIZE、Font、Drawing

2023-09-03 04:48:17 作者:安然失笑 ゝ

System.Drawing.Font 不是XML序列化,因为它没有一个默认的(空的)构造函数。 有一些变通或序列化字体不过?

The classSystem.Drawing.Font is not XML Serializable since it doesn't have a default (empty) constructor. Is there some work around or alternative way to serialize Font nevertheless?

推荐答案

编辑:我更新根据code Regent建议使用 FontConverter ,而preserving能够使用的 SerializableFont 定期字体

I updated the code according to Regent suggestion to use FontConverter, while preserving the ability to use the SerializableFont as regular Font.

public class SerializableFont
{
    public SerializableFont()
    {
        FontValue = null;
    }

    public SerializableFont(Font font)
    {
        FontValue = font;
    }

    [XmlIgnore]
    public Font FontValue { get; set; }

    [XmlElement("FontValue")]
    public string SerializeFontAttribute
    {
        get
        {
            return FontXmlConverter.ConvertToString(FontValue);
        }
        set
        {
            FontValue = FontXmlConverter.ConvertToFont(value);
        }
    }

    public static implicit operator Font(SerializableFont serializeableFont)
    {
        if (serializeableFont == null )
            return null;
        return serializeableFont.FontValue;
    }

    public static implicit operator SerializableFont(Font font)
    {
        return new SerializableFont(font);
    }
}

public static class FontXmlConverter
{
    public static string ConvertToString(Font font)
    {
        try
        {
            if (font != null)
            {
                TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));
                return converter.ConvertToString(font);
            }
            else 
                return null;
        }
        catch { System.Diagnostics.Debug.WriteLine("Unable to convert"); }
        return null;
    }
    public static Font ConvertToFont(string fontString)
    {
        try
        {
            TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));
            return (Font)converter.ConvertFromString(fontString);
        }
        catch { System.Diagnostics.Debug.WriteLine("Unable to convert"); }
        return null;
    }
}

用法:当你有一个字体属性,它声明为 SerializableFont 。这将允许它被序列化,而隐式转换将处理转换为你。

Usage: When you have a Font property, declare it as SerializableFont. This will allow it to be serialized, while the implicit cast will handle the conversion for you.

Font MyFont {get;set;}

写:

SerializableFont MyFont {get;set;}
 
精彩推荐
图片推荐