2016-06-28 8 views
2

나는 주어진 개체의 컬렉션이 있다면, 정말 같은 개체의 속성을 얻을 수 있어요 : 나는 몇 가지가 있어요기본 클래스의는 IEnumerable에서 하위 클래스에서 속성을 얻

var myCollection = new List<Foo>(); 
entities.GetType().GetGenericArguments()[0].GetProperties().Dump(); 

을하지만 내 컬렉션이 기본 클래스의 IEnumerable이고 파생 클래스로 채워진 경우 속성을 나열하는 데 어려움이 있습니다.

public class Foo 
{ 
    public string One {get;set;} 
} 

public class Bar : Foo 
{ 
    public string Hello {get;set;} 
    public string World {get;set;} 
} 

// "Hello", "World", and "One" contained in the PropertyInfo[] collection 
var barCollection = new List<Bar>() { new Bar() }; 
barCollection.GetType().GetGenericArguments()[0].GetProperties().Dump(); 

// Only "One" exists in the PropertyInfo[] collection 
var fooCollection = new List<Foo>() { new Bar() }; 
fooCollection.GetType().GetGenericArguments()[0].GetProperties().Dump(); 

컬렉션이 기본 클래스를 사용하여 선언 되었더라도 컬렉션의 항목 유형을 가져 오는 방법이 있습니까? 만약 Foo이며 FooOne 속성을 갖는 입력 파라미터 T로 표시되는 유형의 특성을 얻기 때문에이다

+0

:

가능한 모든 속성을 얻으려면, 당신은 다음과 같이 목록에있는 모든 오브젝트의 종류를 통해 갈 필요가 시간 정보. –

+0

목록에 다른 유형의 객체가 있다면? 왜 재산이 필요한가요? –

답변

3

. 당신은 컴파일보다는 반복하여 실제 수집 값의 유형을 얻을 수 있습니다

var allProperties = fooCollection 
    .Select(x => x.GetType()) 
    .Distinct() 
    .SelectMany(t => t.GetProperties()) 
    .ToList(); 
+0

고맙습니다. 이것이 제가 찾고 있던 것입니다. 도와 주셔서 감사합니다. –

관련 문제