Как к Системе XmlSerialize. Рисование. Класс шрифта

КлассSystem.Drawing.Font не XML сериализуемый, так как это не имеет (пустого) конструктора по умолчанию.
Есть ли некоторая работа вокруг или альтернативный способ сериализировать Font тем не менее?

11
задан Ronny 21 December 2009 в 13:35
поделиться

5 ответов

Изменить: Я обновил код в соответствии с предложением Регента использовать FontConverter , сохранив при этом возможность использования SerializableFont как обычный шрифт .

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;
    }
}

Использование: если у вас есть свойство Font , объявите его как SerializableFont . Это позволит сериализовать его, в то время как неявное приведение будет обрабатывать преобразование за вас.

Вместо записи:

Font MyFont {get;set;}

Напишите:

SerializableFont MyFont {get;set;}
19
ответ дан 3 December 2019 в 02:52
поделиться

Предложение о том, как это сделать путем реализации сериализуемого класса-оболочки, дается на странице MSDN для класса Font .

4
ответ дан 3 December 2019 в 02:52
поделиться

I use a serializable font, somewhat different from Elad's.

In my serializable data-entities I hide ([XmlIgnore]) the property with the Font type and expose the property with the SerializableFont type, which is "eaten" by the serializer.

Note that this is applicable to the XmlSerializer only.

/// <summary>
/// Font descriptor, that can be xml-serialized
/// </summary>
public class SerializableFont
{
    public string FontFamily { get; set; }
    public GraphicsUnit GraphicsUnit { get; set; }
    public float Size { get; set; }
    public FontStyle Style { get; set; }

    /// <summary>
    /// Intended for xml serialization purposes only
    /// </summary>
    private SerializableFont() { }

    public SerializableFont(Font f)
    {
        FontFamily = f.FontFamily.Name;
        GraphicsUnit = f.Unit;
        Size = f.Size;
        Style = f.Style;
    }

    public static SerializableFont FromFont(Font f)
    {
        return new SerializableFont(f);
    }

    public Font ToFont()
    {
        return new Font(FontFamily, Size, Style,
            GraphicsUnit);
    }
}
4
ответ дан 3 December 2019 в 02:52
поделиться

System.Drawing.Font имеет связанный класс FontConverter , и я бы вручную преобразовал его:

[Serializable]
public class SerializableFont
{
    public SerializableFont()
    {
        this.Font = null;
    }

    public SerializableFont(Font font)
    {
        this.Font = font;
    }

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

    [XmlElement("Font")]
    public string FontString
    {
        get
        {
            if (font != null)
            {
                TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));

                return converter.ConvertToString(this.Font);
            }
            else return null;
        }
        set
        {
            TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));

            this.Font = converter.ConvertFromString(value);
        }
    }
}
2
ответ дан 3 December 2019 в 02:52
поделиться

Попробуйте DataContractSerializer.

        Font fnt = new Font("Arial", 1);
        MemoryStream data = new MemoryStream();
        DataContractSerializer dcs = new DataContractSerializer(typeof(Font), new[] { typeof(FontStyle), typeof(GraphicsUnit) });
        dcs.WriteObject(data, fnt);
        string xml = Encoding.UTF8.GetString(data.ToArray());
1
ответ дан 3 December 2019 в 02:52
поделиться
Другие вопросы по тегам:

Похожие вопросы: