2011-05-09 2 views
1

중첩 된 속성에서 값을 가져와야합니다.중첩 된 속성에서 값을 가져와야합니다.

MainClass에는 Student Class 유형이 있습니다.

MainClass obj = new MainClass(); 

obj.Name = "XII"; 
obj.Students = new List<Students>() 
    { 
     new Students() { ID = "a0", Name = "A" }, 
     new Bridge() { ID = "a1", Name = "B" } 
    }; 

Type t = Type.GetType(obj.ToString()); 
PropertyInfo p = t.GetProperty("Students"); 

object gg = p.GetValue(obj, null); 
var hh = gg.GetType(); 
string propertyType = string.Empty; 

if (hh.IsGenericType) 
    { 
     string[] propertyTypes = hh.ToString().Split('['); 
     Type gggg = Type.GetType(propertyTypes[1].Remove(propertyTypes[1].Length - 1)); 
     foreach (PropertyInfo pro in gggg.GetProperties()) 
      { 
       if (pro.Name.Equals("Name")) 
       { 
        // Get the value here 
       } 
      } 
    } 
+0

목록의 '찾기'메소드를 사용하지 않는 이유는 무엇입니까? – V4Vendetta

+0

정확히 무엇을 찾으려고합니까? 그리고 정말로 반사가 필요합니까? 'Bridge' 클래스는 무엇을위한 것인가? – SWeko

답변

2

먼저 사용합니다. 클래스가 ToString() 메서드를 오버로드하지 않았을 경우에만 작동하며 런타임에 중단됩니다 (있는 경우). 다행히, 모든 클래스는 GetType을() metod있다 (

string[] propertyTypes = hh.ToString().Split('['); 
Type gggg = Type.GetType(propertyTypes[1].Remove(propertyTypes[1].Length - 1) 

은 일반 유형을 지정 유형을 얻기 위해 끔찍한 방법입니다. 그래서 Type t = obj.GetType() 올바른 코드가, 객체에 정의

두 번째 것 이 당신을 위해 작업을 수행하는 방법 GetGenericArguments, 그래서이 코드는 목록 항목에 액세스 실제 문제에 대한 지금

Type[] genericArguments = hh.GetGenericArguments(); 
Type gggg = genericArguments[0]; 

와 함께 변경 될 수 있습니다로. 그렇게하는 가장 좋은 방법은 인덱서를 사용하는 것입니다 ([])의 List<> 클래스. C#에서는 인덱서를 정의 할 때 자동으로 Item이라는 속성으로 전달되며 해당 속성을 사용하여 값을 추출 할 수 있습니다 (Item 이름은 형식 정의에서 추론 할 수 있지만 대부분은 하드 코딩 할 수 있음)

PropertyInfo indexer = hh.GetProperty("Item"); // gets the indexer 

//note the second parameter, that's the index 
object student1 = indexer.GetValue(gg, new object[]{0}); 
object student2 = indexer.GetValue(gg, new object[]{1}); 

PropertyInfo name = gggg.GetProperty("Name"); 
object studentsName1 = name.GetValue(student1, null); // returns "A" 
object studentsName2 = name.GetValue(student2, null); // returns "B" 
0

무시 모두 StudentsBridge 클래스 Equals 방법은 다음 Find를 사용하거나

Type t = Type.GetType(obj.ToString()); 

이 잘못 모든 LINQ

+0

사실 그것이 잘못되었습니다. 'Type.GetType'은 클래스의 이름을 기대하고 그 문자열의 타입을 반환하므로 두번째 라인은 컴파일되지 않습니다 (일반적으로). 첫 번째 라인은 sintaxically correct하지만 클래스가 ToString() 메소드를 오버라이드 할 수 있고, obj.GetType()이 짧고 정확한 버전이기 때문에 바보 같다. – SWeko

+0

@SWeko 정정 해줘서 고마워. – abhilash

+2

@SWeko : 구문 론적으로 – Svish

관련 문제