2010-12-12 69 views
5

我有public static class MyClass其中包含许多public static string参数。通过字符串获取静态属性

继我有一定的价值

string val = "something"; 

使用val我希望能够得到指定的属性 - 像MyClass.something。 我该怎么做?

+0

你想让MyClass.something返回字符串“val”或者你是否试图通过它的名字获取属性值?这个问题有点不清楚,你能给出一个代码的使用示例吗? – sprite 2010-12-12 15:06:55

+0

对不起。我现在没有代码,但回答你的问题,我想通过它的名字获得一个属性值。 – hsz 2010-12-12 15:10:23

回答

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

另一种方法是检查您的代码。恕我直言,通过反射获取属性不是最好的主意。所以如果你重写你的代码,这些属性将不会被存储在静态字段中,而是存储在Dictionary<string, string>中。下面是例子:

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"];} } 
} 

之后,你可以使用MyClass.Property1MyClass.Properties["Property1"]调用它。