2009-08-26 6 views
0

여기 시나리오가 있습니다. 나는 Address 객체를 가진 Person 객체를 가지고있다. 사람은 주소 목록을 가지고 있습니다.개체 속성 반영을 사용하여 모든 개체 만들기!

이제 Person의 속성을 반복하고 싶습니다. List에 도달하면 Address 개체의 개체를 만들고 싶습니다. 내가 어떻게 할 수 있니?

업데이트 :

public class Person 
    { 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 

     private List<Address> _addresses = new List<Address>(); 

     public void AddAddress(Address address) 
     { 
      _addresses.Add(address); 
      address.Person = this; 
     } 

     public List<Address> Addresses 
     { 
      get { return _addresses; } 
      set { _addresses = value; } 
     } 
    } 
var properties = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); 
      foreach(var property in properties) 
      { 
       var propertyType = property.PropertyType; 

       if (!propertyType.IsGenericType) continue; 

       var obj = Activator.CreateInstance(propertyType); 

       var genericType = obj.GetType().GetGenericTypeDefinition(); 

       Console.WriteLine(obj.GetType().Name); 


       var type = property.GetType(); 
      } 

위의 반사 코드가 나에게 목록을 반환하지만이 유형의 목록입니다. 나는 주소 인 Generic Type을 원한다.

+0

Person 클래스의 코드와 의사 코드 스 니펫을 공유하고 싶습니까? –

+0

아, 마치 obj.GetType()처럼 보입니다. GetGenericArguments(); 주소 –

+0

을 반환합니다. 실제로 문제가 해결되지 않았습니다! 리플렉션을 사용하여 List

컬렉션을 반복하는 방법은 무엇입니까? –

답변

0

토니, 주소 클래스에 액세스 할 수 있다면 간단하게이 작업을 수행 할 수 있습니다.

var properties = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); 
      List<Address> retVal; 
      foreach (var property in properties) 
      { 
       var propertyType = property.PropertyType; 
       if (!propertyType.IsGenericType) continue; 


       retVal = property.GetValue(item, new object[] { }) as List<Address>; 

       if (retVal != null) 
        break; 
      } 

      //now you have your List<Address> in retVal 
+0

감사! 많이이 질문에 대한 답변 –