2011-07-01 3 views
1
class ClassA 
{ 
    public ClassB myProp {get;set;} 
} 

class ClassB 
{ 
    public ClassC anotherProp {get;set;} 
} 

class ClassC 
{ 
    public string Name {get;set;} 
} 

ClassA 유형의 개체가 있습니다. 어떻게, 반성에 의해 ClassC의 Name 속성 값을 얻기 위해 재귀 적으로 반복할까요?클래스 속성 트리를 반복하는 방법은 무엇입니까?

답변

0

좋습니다.

var dataPath = column.SortMemberPath.Split(new char[] { '.' }); 

[...] 

foreach (var item in (System.Collections.IList)myObject) 
{ 
    var newItem = item; 

    foreach (var path in dataPath) 
    { 
     var actalValue = newItem.GetType().GetProperty(path).GetValue(newItem, null); 
     newItem = actalValue; //it does the trick 
    } 

    now, the newItem is my wanted property value 
} 
), 나는 재귀없이 트리를 반복 parh 분할 후,

ClassB.ClassC.Name 

다음 : 의 나는 내가 할 싶어 가치 속성에 대한 경로를 가지고 있다고 가정 해 봅시다

3

나는 당신이 달성하기를 원하는 바를 약간 개략적으로 설명했다. 제 생각에 당신은 ClassA로 시작하여 결국 속성을 거쳐 ClassC에 도달하려고합니다. 이를 위해서는 재귀 프로그래밍을하는 방법과 Reflection에 대한 지식을 거의 이해해야합니다. 다음은 이전에 사용한 코드의 수정 된 버전입니다 (find here). 이것은 무엇을

private void SerializeObject(object obj) { 

    Type type = obj.GetType(); 

    foreach (PropertyInfo info2 in type.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) 
    { 
     MethodInfo getMethod = info2.GetGetMethod(true); 

     if (getMethod != null) 
      SerializeObject(getMethod.Invoke(obj, null)); 
    } 

} 

각 속성을 통해 도보 및 속성을 실행하고 같은 SerializeObject 메서드를 호출하여 그것을 통해 걸을 수 있도록 반환되는 객체를 얻기 위해 각 속성의 get 메소드를 사용합니다.

관련 문제