在 C# 中将字符串转换为画笔/画笔颜色名称

2024-01-05

我有一个配置文件,开发人员可以通过传入字符串来指定文本颜色:

 <text value="Hello, World" color="Red"/>

与其使用巨大的 switch 语句来查找所有可能的颜色,不如直接使用 System.Drawing.Brushes 类中的属性,这样在内部我可以这样说:

 Brush color = Brushes.Black;   // Default

 // later on...
 this.color = (Brush)Enum.Parse(typeof(Brush), prasedValue("color"));

除了 Brush/Brushes 中的值不是枚举之外。所以 Enum.Parse 没有给我带来任何快乐。建议?


回顾之前的所有答案,将字符串转换为颜色或画笔的不同方法:

// best, using Color's static method
Color red1 = Color.FromName("Red");

// using a ColorConverter
TypeConverter tc1 = TypeDescriptor.GetConverter(typeof(Color)); // ..or..
TypeConverter tc2 = new ColorConverter();
Color red2 = (Color)tc.ConvertFromString("Red");

// using Reflection on Color or Brush
Color red3 = (Color)typeof(Color).GetProperty("Red").GetValue(null, null);

// in WPF you can use a BrushConverter
SolidColorBrush redBrush = (SolidColorBrush)new BrushConverter().ConvertFromString("Red");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C# 中将字符串转换为画笔/画笔颜色名称 的相关文章

随机推荐