2009-07-17 17 views
24

Ho un'interfaccia generica, ad esempio IGeneric. Per un dato tipo, voglio trovare gli argomenti generici che un programma di classe tramite IGeneric.Ottenere argomenti tipo di interfacce generiche implementate da una classe

E 'più chiaro in questo esempio:

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) } 

Qual è l'implementazione di GetTypeArgsOfInterfacesOf (tipo T)?

Nota: si può presumere che il metodo GetTypeArgsOfInterfacesOf sia scritto specificamente per IGeneric.

Modifica: Si noti che sto specificatamente chiedendo come filtrare l'interfaccia IGeneric da tutte le interfacce implementate da MyClass.

correlati: Finding out if a type implements a generic interface

risposta

35

di limitarla a solo un sapore specifico di un'interfaccia generica è necessario per ottenere la definizione di tipo generico e confrontare con la "aperto" di interfaccia (IGeneric<> - nota n "T" specificata):

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 

O come LINQ query sintassi:

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

Ok ma questo riguarda EvilType di IDontWantThis . Non voglio il EvilType. –

+0

Risolto, solo bisogno di una semplice condizione sul Dove(). –

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{ } 
Problemi correlati