获取类实现的generics接口的类型参数

我有一个通用接口,比如IGeneric。 对于给定的类型,我想找到一个类通过IGeneric实现的generics参数。

在这个例子中更清楚:

Class MyClass : IGeneric, IGeneric, IDontWantThis { ... } Type t = typeof(MyClass); Type[] typeArgs = GetTypeArgsOfInterfacesOf(t); // At this point, typeArgs must be equal to { typeof(Employee), typeof(Company) } 

GetTypeArgsOfInterfacesOf(Type t)的实现是什么?

注意:可以假设GetTypeArgsOfInterfacesOf方法是专门为IGeneric编写的。

编辑:请注意我特别询问如何从MyClass实现的所有接口中过滤掉IGeneric接口。

相关: 确定类型是否实现了通用接口

要将它限制为通用接口的特定风格,您需要获取generics类型定义并与“open”接口进行比较( IGeneric<> – 注意没有指定“T”):

 List genTypes = new List(); 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(); 
  Type t = typeof(MyClass); List Gtypes = new List(); foreach (Type it in t.GetInterfaces()) { if ( it.IsGenericType && it.GetGenericTypeDefinition() == typeof(IGeneric<>)) Gtypes.AddRange(it.GetGenericArguments()); } public class MyClass : IGeneric, IGeneric, IDontWantThis { } public interface IGeneric{} public interface IDontWantThis{} public class Employee{ } public class Company{ } public class EvilType{ }