获取各类执行具体的开放式泛型类型 [英] 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<>
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 interface ConcreteUserRepo : IUserRepository
{}
public interface IUserRepository : IRepository<User>
{}
public interface IRepository<User>
{}
public class User
{}
这篇关于获取各类执行具体的开放式泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文