请考虑以下示例:
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+)中实现为StudentRepo
的所有类(PersonRepo
和IRepository<T>
。
当我使用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();