从字符串名称返回FontStyle

use*_*014 5 c# fonts parsing

我想写一个函数,它将返回FontStyle并将字符串作为参数

FontStyle f = function ("Italic"); // FontStyles.Italic
Run Code Online (Sandbox Code Playgroud)

我不想写Switch case或if else语句来做同样的事情.

它可以用不区分大小写的字符串吗?

FontStyle f = function ("italic");
FontStyle f = function ("itAlic"); 
Run Code Online (Sandbox Code Playgroud)

应该返回相同.

小智 10

在C#中,它只是一个枚举.所以你可以像这样转换它:

FontStyle f = (FontStyle)Enum.Parse(typeof(FontStyle), "Italic", true);
Run Code Online (Sandbox Code Playgroud)


Dan*_*rth 7

您可以使用反射:

var propertyInfo = typeof(FontStyles).GetProperty("Italic",
                                                  BindingFlags.Static |
                                                  BindingFlags.Public |
                                                  BindingFlags.IgnoreCase);
FontStyle f = (FontStyle)propertyInfo.GetValue(null, null);
Run Code Online (Sandbox Code Playgroud)