获取类实现的通用接口的类型参数

问题描述:

我有一个通用接口,比如说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

要限制它只是通用接口的特殊味道,你需要得到泛型类型定义,并比较“打开”界面(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(); 

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

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