2009-07-17 7 views
24

제네릭 인터페이스가 있습니다 (예 : IGeneric). 주어진 타입에 대해서, 클래스가 IGeneric을 통해 imlements하는 일반 인자를 찾고 싶습니다.클래스가 구현하는 제네릭 인터페이스의 형식 인수 얻기

그것은이 예에서 더 분명하다

Class MyClass : IGeneric<Employee>, IGeneric<Company>, IDontWantThis<EvilType> { ... } 

Type t = typeof(MyClass); 
Type[] typeArgs = GetTypeArgsOfInterfacesOf(t); 

// At this point, typeArgs must be equal to { typeof(Employee), typeof(Company) } 

GetTypeArgsOfInterfacesOf (T 형)의 구현은 무엇입니까?

참고 : GetTypeArgsOfInterfacesOf 메서드가 특별히 IGeneric 용으로 작성되었다고 가정 할 수 있습니다.

편집 : MyClass가 구현하는 모든 인터페이스에서 IGeneric 인터페이스를 필터링하는 방법을 구체적으로 묻는 중입니다.

관련 : Finding out if a type implements a generic interface

답변

35

당신이 인터페이스 (IGeneric<> 제네릭 형식 정의를 얻을하고 "열기"를 비교할 필요가 일반적인 인터페이스의 단지 특정 풍미를 제한하려면 - 지정되지 "T"를주의하지) :

List<Type> genTypes = new List<Type>(); 
foreach(Type intType in t.GetInterfaces()) { 
    if(intType.IsGenericType && intType.GetGenericTypeDefinition() 
     == typeof(IGeneric<>)) { 
     genTypes.Add(intType.GetGenericArguments()[0]); 
    } 
} 
// now look at genTypes 

또는 LINQ 쿼리 구문과 같은 :

Type[] typeArgs = (
    from iType in typeof(MyClass).GetInterfaces() 
    where iType.IsGenericType 
     && iType.GetGenericTypeDefinition() == typeof(IGeneric<>) 
    select iType.GetGenericArguments()[0]).ToArray(); 
13
typeof(MyClass) 
    .GetInterfaces() 
    .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IGeneric<>)) 
    .SelectMany(i => i.GetGenericArguments()) 
    .ToArray(); 
+0

하지만 여기에는 EvontType of IDontWantThis 이 관련됩니다. 나는 EvilType을 원하지 않는다. –

+0

고정되었으므로 Where()에 간단한 조건이 필요했습니다. –

2
Type t = typeof(MyClass); 
      List<Type> Gtypes = new List<Type>(); 
      foreach (Type it in t.GetInterfaces()) 
      { 
       if (it.IsGenericType && it.GetGenericTypeDefinition() == typeof(IGeneric<>)) 
        Gtypes.AddRange(it.GetGenericArguments()); 
      } 


public class MyClass : IGeneric<Employee>, IGeneric<Company>, IDontWantThis<EvilType> { } 

    public interface IGeneric<T>{} 

    public interface IDontWantThis<T>{} 

    public class Employee{ } 

    public class Company{ } 

    public class EvilType{ } 
관련 문제