Get static property by string

2020-08-27 01:19发布

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 ?

标签: c#
2条回答
仙女界的扛把子
2楼-- · 2020-08-27 01:40
PropertyInfo propertyInfo = typeof(MyClass).GetProperty("something");
string something = (string) propertyInfo.GetValue(null, null);
查看更多
男人必须洒脱
3楼-- · 2020-08-27 01:46

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"].

查看更多
登录 后发表回答