C#:如何找到实现IRepo<;T1、T2>;

本文关键字:lt T1 gt T2 IRepo 何找 实现 | 更新日期: 2023-09-27 17:58:47

我有一个通用接口:IRepo<T1, T2>。我有几个类实现了这个接口:

class UserRepo:       IRepo<UserEntity, long>
class AdminUserRepo:  IRepo<UserEntity, long>
class OrderRepo:      IRepo<Order, Guid>

如何扫描程序集以查找:

  • 找到实现IRepo<UserEntity, long>UserRepoAdminUserRepoUserlong在运行时是已知的)
  • 查找实现IRepo<T1, T2>的所有repo类(T1和T2未知)

C#:如何找到实现IRepo<;T1、T2>;

  • 查找实现封闭通用接口的类型

    assembly.GetTypes().Where(type =>
        typeof(IRepo<UserEntity, long>).IsAssignableFrom(type))
    
  • 查找实现开放通用接口的类型

    assembly.GetTypes().Where(type => type.GetInterfaces()
        .Any(i => i.IsGenericType &&
                  i.GetGenericTypeDefinition() == typeof(IRepo<,>)))
    

我在Linq中使用这段代码,希望它能有所帮助。

var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .Where(p => type.IsAssignableFrom(p));