2016-07-27 81 views
1

我有一个通用接口:IRepo<T1, T2>。 我有实现这个接口几类:C#:如何找到实现IRepo <T1, T2>的类?

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

我如何可以扫描组件,以发现:

  • 找到UserRepoAdminUserRepo它们实现IRepo<UserEntity, long>Userlong在运行时都知道)
  • 找到所有实施IRepo<T1, T2>的回购类(T1和T2未知)
+0

是否所有的类都在同一个程序集中? – acostela

+0

如果我们假设存在另一个类 - “类OtherOrderRepo:OrderRepo”(即,它不*直接*实现接口,但是从一个类继承)应该包含在结果中吗? –

+0

@acostela是的,他们在同一个程序集中。 – staticcast

回答

1
  • 要查找的类型实现一个封闭的通用接口

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

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

我用这段代码Linq我希望它有帮助。

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

这对于打开的泛型类型不起作用。 – thehennyy

相关问题