请考虑以下示例:
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 {}
我想查找用C#(。NET Core 3+)实现的iRepository
的所有类(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
,iRepository
)。 您需要检查类型的接口是否为泛型(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();