如何找到在 C# .NET Core 中实现嵌套接口的所有 类(类型)?

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 {}

我想找到在 C# (.NET Core 3+) 中实现 IRepository<T> 的所有 类(StudentRepoPersonRepo)。

当我使用 IStudentRepositoryIPersonRepository 查找类型时,一切正常,但无法通过搜索 typeof(IRepository<>)!

这段代码returns没什么

var repoTypes = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(s => s.GetTypes())
                .Where(x => x.GetInterfaces().Containes(typeof(IRepository<>)))
                .ToList()
                ;

谁能帮帮我?

this block of code returns nothing

因为 none 个存储库实现了开放通用接口 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();