Get all types implementing specific open generic type

后端 未结 4 1973
滥情空心
滥情空心 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:47

    This will return all types that inherit a generic base class. Not all types that inherit a generic interface.

    var AllTypesOfIRepository = from x in Assembly.GetAssembly(typeof(AnyTypeInTargetAssembly)).GetTypes()
     let y = x.BaseType
     where !x.IsAbstract && !x.IsInterface &&
     y != null && y.IsGenericType &&
     y.GetGenericTypeDefinition() == typeof(IRepository<>)
     select x;
    

    This will return all types, including interfaces, abstracts, and concrete types that have the open generic type in its inheritance chain.

    public static IEnumerable GetAllTypesImplementingOpenGenericType(Type openGenericType, Assembly assembly)
    {
        return from x in assembly.GetTypes()
                from z in x.GetInterfaces()
                let y = x.BaseType
                where
                (y != null && y.IsGenericType &&
                openGenericType.IsAssignableFrom(y.GetGenericTypeDefinition())) ||
                (z.IsGenericType &&
                openGenericType.IsAssignableFrom(z.GetGenericTypeDefinition()))
                select x;
    }
    

    This second method will find ConcreteUserRepo and IUserRepository in this example:

    public class ConcreteUserRepo : IUserRepository
    {}
    
    public interface IUserRepository : IRepository
    {}
    
    public interface IRepository
    {}
    
    public class User
    {}
    

提交回复
热议问题