[英]How to find all classes (types) that are implemented a nested interface in C# .NET Core?
請考慮以下示例:
public interface IRepository<T> {} // NESTED
public class Student {}
public class Person {}
public interface IStudentRepository : IRepository<Student> {}
public interface IPersonRepository : IRepository<Person> {}
public class StudentRepo : IStudentRepository {}
public class PersonRepo : IPersonRepository {}
我想找到在IRepository<T>
(.NET Core 3+)中實現的所有類( StudentRepo
和PersonRepo
)。
當我使用IStudentRepository
或IPersonRepository
查找類型時,一切正常,但無法通過搜索typeof(IRepository<>)
!
此代碼塊不返回任何內容
var repoTypes = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(x => x.GetInterfaces().Containes(typeof(IRepository<>)))
.ToList()
;
誰能幫我?
此代碼塊不返回任何內容
因為沒有一個存儲庫實現開放的通用接口IRepository<>
,所以它們實現了構造的接口( IRepository<Student>
, IRepository<Person>
)。 您需要檢查類型的接口是否是通用的( Type.IsGenericType
)並且它的通用類型定義( Type.GetGenericTypeDefinition()
)等於typeof(IRepository<>)
:
var repoTypes = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(x => !x.IsInterface && x.GetInterfaces()
.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IRepository<>)))
.ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.