本文介绍了在 C# 中将字符串转换为画笔/画笔颜色名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个配置文件,开发人员可以在其中通过传入字符串来指定文本颜色:
I have a configuration file where a developer can specify a text color by passing in a string:
<text value="Hello, World" color="Red"/>
与其用一个巨大的 switch 语句来查找所有可能的颜色,不如使用 System.Drawing.Brushes 类中的属性,这样我在内部可以这样说:
Rather than have a gigantic switch statement look for all of the possible colors, it'd be nice to just use the properties in the class System.Drawing.Brushes instead so internally I can say something like:
Brush color = Brushes.Black; // Default
// later on...
this.color = (Brush)Enum.Parse(typeof(Brush), prasedValue("color"));
除了 Brush/Brushes 中的值不是枚举.所以 Enum.Parse 没有给我带来快乐.建议?
Except that the values in Brush/Brushes aren't enums. So Enum.Parse gives me no joy. Suggestions?
推荐答案
回顾所有以前的答案,将字符串转换为颜色或画笔的不同方法:
Recap of all previous answers, different ways to convert a string to a Color or Brush:
// 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");
这篇关于在 C# 中将字符串转换为画笔/画笔颜色名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!