Graviton
Graviton

Reputation: 83254

Get Static Property By the Name of the Property

In ImageFormat, there are a few properties such as Png, Tiff etc.

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

Here's the code

[Test]
public void GetPng()
{
    Assert.AreEqual(ImageFormat.Png, GetImageFormat("Png"));  //how to construct a GetImageFormat function?
}

Upvotes: 3

Views: 194

Answers (3)

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102408

public static void Main()
{
    typeof(ImageFormat).GetProperty("GetPng", BindingFlags.Public |
                                              BindingFlags.Static);
}

Upvotes: 4

Julien Roncaglia
Julien Roncaglia

Reputation: 17837

static ImageFormat GetImageFormat(string name)
{
    return (ImageFormat)typeof(ImageFormat)
        .GetProperty(name)
        .GetValue(null, null);
}

Upvotes: 2

Mark Seemann
Mark Seemann

Reputation: 233150

PropertyInfo pi =  typeof(ImageFormat)
    .GetProperty("Png", BindingFlags.Static | BindingFlags.Public);

Upvotes: 2

Related Questions