lundi 15 juin 2015

Find classes which inherits from a generic class using reflection

I need a way to filter my assemblies to get all classes that inherits from a generic class. I have found some posts but they are most like how to check the inheritence(e.g. here and here). But these posts didn't helped me.

All my classes inherits from a specific one, called BaseRepository<T>, but some classes can inherit from InterventionBaseRepository<T>(which inherits from BaseRepository<T> as well). I need to find them. This is my code until now:

var q = from t in Assembly.GetExecutingAssembly().GetTypes()
        where t.IsClass && 
             (t.Namespace != null &&
              t.Namespace.StartsWith("AgroWeb.Core.Data.Repository"))
        select t;

So, in short, the query above gets all my classes by namespace which I need to find among them those who inherits from InterventionBaseRepository<T>.

An example of a signature of a class which must be found:

public class CityRepository : InterventionBaseRepository<City>, ICityRepository

And the InterventionBaseRepository declaration:

public class InterventionBaseRepository<T> : BaseRepository<T>
    where T : Entity

I tried to use IsAssignableFrom() as said in those posts linked above in the query like this:

t.IsAssignableFrom(typeof(InterventionBaseRepository<Entity>))





Aucun commentaire:

Enregistrer un commentaire