這將返回所有繼承泛型基類的類型。不是所有繼承通用接口的類型。
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;
這將返回所有類型,包括接口,摘要,並且在其繼承鏈的開放式泛型類型的具體類型。
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在這個例子:
public interface ConcreteUserRepo : IUserRepository
{}
public interface IUserRepository : IRepository<User>
{}
public interface IRepository<User>
{}
public class User
{}
是的,但是隻有當它在同一個程序集中時纔會得到concreterepo和irepo。但這絕對沒問題。 – Rookian 2011-12-27 15:22:53
好抓!我們必須小心加載所有相關的程序集,而不僅僅是掃描當前加載的程序集。下面是關於加載所有程序集的一個SO:http://stackoverflow.com/questions/2384592/c-net-is-there-a-way-to-force-all-referenced-assemblies-to-be- load-into- – 2011-12-27 15:42:18
typeof(IRepository <>)僅適用於泛型類型具有單個泛型參數的情況。對於具有多個泛型類型參數的類型的任何想法? – dotnetguy 2015-12-08 00:29:59