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

问题描述 投票:0回答:1

请考虑以下示例:

    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的所有类(PersonRepoIRepository<T>

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

此代码块不返回任何内容

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

有人可以帮我吗?

c# reflection system.reflection
1个回答
0
投票

此代码块不返回任何内容

由于您的存储库中没有一个实现开放的通用接口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();
© www.soinside.com 2019 - 2024. All rights reserved.