2010-12-12 11 views
5

public static class MyClass에는 많은 public static string 매개 변수가 있습니다. MyClass.something처럼 -문자열로 정적 속성 가져 오기

내가 지정된 속성을 얻을 수 있기를 원하는 val 것을 사용하여 어떤 값

string val = "something"; 

이 다음. 어떻게하면됩니까?

+0

MyClass.something이 문자열 "val"을 반환하거나 이름으로 속성 값을 가져 오려고합니까? 질문은 약간 불분명합니다. 코드의 사용 예제를 줄 수 있습니까? – sprite

+0

죄송합니다. 지금 당장은 코드가 없지만 질문에 대답하면 이름으로 속성 값을 얻고 싶습니다. – hsz

답변

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

다른 방법은 코드를 검토하는 것입니다. IMHO, 리플렉션을 통해 속성을 얻는 것이 가장 좋은 방법은 아닙니다. 따라서 코드를 다시 작성하면 해당 속성은 정적 필드가 아닌 Dictionary<string, string>에 저장됩니다. 당신이 MyClass.Property1 또는 MyClass.Properties["Property1"]를 사용하여 호출 할 수 있습니다 그 후

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

: 다음은 예입니다.