2010-07-22 2 views
3

C# 3.5에서 리플렉션을 사용하여 객체의 유형이 List<MyObject>인지 확인하는 방법이 있습니까? 예 :C#에서 목록 유형을 결정하십시오

Type type = customerList.GetType(); 

//what should I do with type here to determine if customerList is List<Customer> ? 

고마워요.

답변

6

당신이 실제로 할 것을 List<something>을 확인하여 당신은 아마 약간의 방어로 할 것, 루카스의 응답에 추가하려면 :

Type type = customerList.GetType(); 
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) 
    itemType = type.GetGenericArguments()[0]; 
else 
    // it's not a list at all 

편집 : 위의 코드는 말한다, '어떤 종류의 목록인가?' 답장을

isListOfMyObject = typeof<List<MyObject>>.IsAssignableFrom(type) 
+0

감사합니다 : 당신은 모두가 Type 인 경우,

isListOfMyObject = customerList is List<MyObject> 

을 또는 : 대답 '이것을 List<MyObject>?이다'하려면 정상으로 is 연산자를 사용 – Victor

0
Type[] typeParameters = type.GetGenericArguments(); 
if(typeParameters.Contains(typeof(Customer))) 
{ 
    // do whatever 
} 
관련 문제