2009-07-17 98 views
24

我有一個通用接口,比如說IGeneric。對於給定的類型,我想通過IGeneric找到一個類通用的參數。獲取類實現的通用接口的類型參數

更清楚在這個例子:

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的IDontWantThis 。我不想要EvilType。 – 2009-07-17 08:58:47

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{ } 
相關問題