按字符串获取静态属性

时间:2010-12-12 14:58:48

标签: c#

我有public static class MyClass,其中包含许多public static string个参数。

以下我有一些价值

string val = "something";

使用val我希望能够获得指定的属性 - 例如MyClass.something。 我怎么能这样做?

2 个答案:

答案 0 :(得分:14)

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

答案 1 :(得分: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"]来调用它。

相关问题