Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use reflection to return all classes subclassing from a generic, without giving a specific generic type

I am trying to write a method using reflection to return all classes that are subclasses of a class that uses generics, without being limited by the generic type. So for example, in EF I want to find all mapping classes. The classes are setup like:

public class clientMap : EntityTypeConfiguration<Client> {}

I want to find all classes in my assembly that is a subclass of of EntityTypeConfiguration<T>, without specifying Client as T specifically. I want to return the entity type configuration for all classes in my application without hardcoding it.

Without generics I would loop through the types in the assembly, check if type.IsSubclassOf(typeof(BaseClass)), however I am not sure how to do this when dealing with generics.

like image 967
KallDrexx Avatar asked Jun 21 '11 14:06

KallDrexx


1 Answers

I believe that you want something like this:

static class TypeExtensions {
    public static bool IsDerivedFromOpenGenericType(
        this Type type,
        Type openGenericType
    ) {
        Contract.Requires(type != null);
        Contract.Requires(openGenericType != null);
        Contract.Requires(openGenericType.IsGenericTypeDefinition);
        return type.GetTypeHierarchy()
                   .Where(t => t.IsGenericType)
                   .Select(t => t.GetGenericTypeDefinition())
                   .Any(t => openGenericType.Equals(t));
    }

    public static IEnumerable<Type> GetTypeHierarchy(this Type type) {
        Contract.Requires(type != null);
        Type currentType = type;
        while (currentType != null) {
            yield return currentType;
            currentType = currentType.BaseType;
        }
    }
}

These tests pass:

class Foo<T> { }
class Bar : Foo<int> { }
class FooBar : Bar { }

[Fact]
public void BarIsDerivedFromOpenGenericFoo() {
    Assert.True(typeof(Bar).IsDerivedFromOpenGenericType(typeof(Foo<>)));
}

[Fact]
public void FooBarIsDerivedFromOpenGenericFoo() {
    Assert.True(typeof(FooBar).IsDerivedFromOpenGenericType(typeof(Foo<>)));
}

[Fact]
public void StringIsNotDerivedFromOpenGenericFoo() {
    Assert.False(typeof(string).IsDerivedFromOpenGenericType(typeof(Foo<>)));
}
like image 195
jason Avatar answered Sep 25 '22 16:09

jason