簡體   English   中英

如何在 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 {}

我想找到在IRepository<T> (.NET Core 3+)中實現的所有類( StudentRepoPersonRepo )。

當我使用IStudentRepositoryIPersonRepository查找類型時,一切正常,但無法通過搜索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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM