2013-07-15 4 views
0

동일한 속성을 가진 다른 클래스가 있어야하며 클래스의 peoperties에 동적으로 액세스하고 싶습니다. 클래스의 속성에 동적으로 액세스하기

public Class1 
{ 
public const prop1="Some"; 
} 
public Class2 
{ 
public const prop1="Some"; 
} 

그리고

내 코드에서 나는이

string classname="Session["myclass"].ToString();";//Say I have Class1 now. 

처럼 내 클래스 이름을 얻고있다 그리고 나는 prop1 값을 얻을합니다.

Something like 
string mypropvalue=classname+".prop1";//my expected result is Some 

/// 타입 = 일반 Type.GetType (클래스 명);

정적이

+0

를 스캔
그냥 개체를 전달을 클래스 이름에서. –

+0

나는 똑같이 시도하지만 올바르게 할 수는 없다. – Nagaraj

+0

리플렉션을 사용하는 방법을 보여주는 코드입니다. – slavoo

답변

0

Reflection

var nameOfProperty = "prop1"; 
var propertyInfo = Class1Object.GetType().GetProperty(nameOfProperty); 
var value = propertyInfo.GetValue(myObject, null); 

을 받고 저를 도와주세요 :

var nameOfProperty = "prop1"; 
var propertyInfo = typeof(Class1).GetProperty("prop1", BindingFlags.Static); 
var value = propertyInfo.GetValue(myObject, null); 

Class reference from string

편집 (I 예 만든) :

class Program 
    { 
     static void Main(string[] args) 
     { 

      var list = Assembly.Load("ConsoleApplication4").GetTypes().ToList(); 
      Type ty = Type.GetType(list.FirstOrDefault(t => t.Name == "Foo").ToString()); 
      //This works too: Type ty = Type.GetType("ConsoleApplication4.Foo"); 
      var prop1 
       = ty.GetProperty("Temp", BindingFlags.Static | BindingFlags.Public); 


      Console.WriteLine(prop1.GetValue(ty.Name, null)); 
      Console.ReadLine(); 
     } 

    } 

    public static class Foo 
    { 
     private static string a = "hello world"; 
     public static string Temp 
     { 
      get 
      { 
       return a; 
      } 
     } 
    } 

Msdn

+0

내 클래스 이름이 세션에서 검색됩니다. – Nagaraj

+0

@Cherry 업데이트 게시물 – slavoo

+0

Thnks .It For Work For me .. 그리고 우리는 "a"에 직접 액세스합니까? – Nagaraj

0

동적 객체 프론 속성 값 가져 기능에 따라 사용할 수 있습니다 : 동적 속성 값을 얻기 위해 반사를 사용할 수 & 속성 이름을

public static object GetPropValue(object src, string propName) 
{ 
    return src.GetType().GetProperty(propName).GetValue(src, null); 
} 
+0

정적 클래스의 값을 얻는 방법 속성 – Nagaraj

+0

참조 http://stackoverflow.com/questions/1487867/ c-sharp-get-of-static-properties-from-static-class –

관련 문제