从图形命名空间将字符串转换为类

时间:2019-05-02 09:46:52

标签: c#

我有一个代表字典的接口。此接口将字符串作为键和值。我需要在其中存储一些字体和颜色,以后再阅读。因此,对于此集合,只能使用字符串类型。

幸运的是,我可以使用ColorFont.ToString()类转换为字符串,所以

collection.Add("Font", font.ToString());
collection.Add("FontColor", fontColor.ToString());

可以解决问题。不幸的是,当我从集合中读取它们时,我无法将字符串转换回Font / Color。

例如

string rawFontColor = myColor.ToString();
Color fontColor = (Color)rawFontColor;

string rawFont = myFont.ToString();
Font font = (Font)rawFont;

不起作用。正确转换它们的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

您在评论中有足够的信息可以执行此操作:

TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));
var collection = new Dictionary<string, string>();

collection.Add("Font", converter.ConvertToString(new Font("Microsoft Sans Serif", 8.25F, 
                       FontStyle.Strikeout, GraphicsUnit.Pixel)));

collection.Add("FontColor", Color.Aqua.ToArgb().ToString());

Color fontColor = Color.FromArgb(int.Parse(collection["FontColor"]));
Font font = (Font)converter.ConvertFromString(collection["Font"]);

Console.WriteLine(fontColor.Name);
Console.WriteLine(font.ToString());