获取实现特定开放泛型类型的所有类型 [英] Get all types implementing specific open generic type
本文介绍了获取实现特定开放泛型类型的所有类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取实现特定开放泛型类型的所有类型?
How do I get all types that implementing a specific open generic type?
例如:
public interface IUserRepository : IRepository<User>
查找所有实现 IRepository<>
的类型.
Find all types that implement IRepository<>
.
public static IEnumerable<Type> GetAllTypesImplementingOpenGenericType(Type openGenericType, Assembly assembly)
{
...
}
推荐答案
这将返回所有继承通用基类的类型.并非所有类型都继承了通用接口.
This will return all types that inherit a generic base class. Not all types that inherit a generic interface.
var AllTypesOfIRepository = from x in Assembly.GetAssembly(typeof(AnyTypeInTargetAssembly)).GetTypes()
let y = x.BaseType
where !x.IsAbstract && !x.IsInterface &&
y != null && y.IsGenericType &&
y.GetGenericTypeDefinition() == typeof(IRepository<>)
select x;
这将返回所有类型,包括在其继承链中具有开放泛型类型的接口、抽象和具体类型.
This will return all types, including interfaces, abstracts, and concrete types that have the open generic type in its inheritance chain.
public static IEnumerable<Type> GetAllTypesImplementingOpenGenericType(Type openGenericType, Assembly assembly)
{
return from x in assembly.GetTypes()
from z in x.GetInterfaces()
let y = x.BaseType
where
(y != null && y.IsGenericType &&
openGenericType.IsAssignableFrom(y.GetGenericTypeDefinition())) ||
(z.IsGenericType &&
openGenericType.IsAssignableFrom(z.GetGenericTypeDefinition()))
select x;
}
第二种方法将在此示例中找到 ConcreteUserRepo 和 IUserRepository:
This second method will find ConcreteUserRepo and IUserRepository in this example:
public class ConcreteUserRepo : IUserRepository
{}
public interface IUserRepository : IRepository<User>
{}
public interface IRepository<User>
{}
public class User
{}
这篇关于获取实现特定开放泛型类型的所有类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文