Get all types implementing specific open generic type

后端 未结 4 1977
滥情空心
滥情空心 2020-12-01 10:05

How do I get all types that implementing a specific open generic type?

For instance:

public interface IUserRepository : IRepository
         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 10:56

    You can use the following code to get all types that implement IRepository<> interface:

    List typesImplementingIRepository = new List();
    IEnumerable allTypesInThisAssembly = Assembly.GetExecutingAssembly().GetTypes();
    
    foreach (Type type in allTypesInThisAssembly)
    {
        if (type.GetInterface(typeof(IRepository<>).Name.ToString()) != null)
        {
            typesImplementingIRepository.Add(type);
        }
    }
    

提交回复
热议问题