Get static property by property name

There ImageFormatare several properties, such as Png, Tiffetc.

Now, if a string is given, is it possible to get the corresponding static property?

Here is the code

[Test]
public void GetPng()
{
    Assert.AreEqual(ImageFormat.Png, GetImageFormat("Png"));  //how to construct a GetImageFormat function?
}
+3
source share
3 answers
static ImageFormat GetImageFormat(string name)
{
    return (ImageFormat)typeof(ImageFormat)
        .GetProperty(name)
        .GetValue(null, null);
}
+2
source
public static void Main()
{
    typeof(ImageFormat).GetProperty("GetPng", BindingFlags.Public |
                                              BindingFlags.Static);
}
+4
source
PropertyInfo pi =  typeof(ImageFormat)
    .GetProperty("Png", BindingFlags.Static | BindingFlags.Public);
+2
source

Source: https://habr.com/ru/post/1755525/


All Articles