2016-07-27 25 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

相關問題