Get static property by string

2020-08-27 01:45发布

问题:

I have public static class MyClass which contains many public static string parameters.

Following I have some value

string val = "something";

Using that val I want to be able to get specified property - like MyClass.something. How can I do that ?

回答1:

PropertyInfo propertyInfo = typeof(MyClass).GetProperty("something");
string something = (string) propertyInfo.GetValue(null, null);


回答2:

Another way is to review your code. IMHO, Getting properties through Reflection is not the best idea. So if you rewrite your code, that properties would be stored not in static fields, but in Dictionary<string, string>. Here is example:

public static class MyClass
{
    public static readonly Dictionary<string, string> Properites = new Dictionary<string, string>();

    public string Property1 { get {return Properties["Property1"];} }
    public string Property2 { get {return Properties["Property2"];} }
}

After that you can call it using MyClass.Property1 or MyClass.Properties["Property1"].



标签: c#