lundi 8 avril 2019

Is there a way to get the type of an inherited generic class using reflection?

I have this as my class signature:

public class LocationRule : IRule<Location>

I am trying to use reflection to access the type of the implementation of IRule.

Using this code

Assembly.GetTypes()
  .Where(type => typeof(IRule<Location>).IsAssignableFrom(type) 
    && !type.IsInterface)

I can get the classes that inherit this specific implementation of IRule. However there is no way to dynamically insert a type into this expression like so.

Assembly.GetTypes()
  .Where(type => typeof(IRule<typeof(AnotherClass)>).IsAssignableFrom(type) 
    && !type.IsInterface)

Is there away to find all classes that implement IRule<> and then find out all the types that are implemented?

public class LocationRule : IRule<Location>
public class NameRule : IRule<Name>

Is there a way to get hold of each of these types? Name and Location, so I can place them in a Dictionary<TypeOfIRuleGeneric, TypeOfRuleClass> i.e Key = Location, Value = LocationRule?

Thanks.





Aucun commentaire:

Enregistrer un commentaire