提问者:小点点

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


请考虑以下示例:

    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的所有类(StudentRepoPersonRepo)。

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

此代码块不返回任何内容

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

有人能帮我吗?


共1个答案

匿名用户

此代码块不返回任何内容

因为没有一个存储库实现开放的泛型接口iRepository,所以它们实现了构造的接口(iRepositoryiRepository)。 您需要检查类型的接口是否为泛型(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();