dimanche 18 juin 2017

Find all types truly assignable to variable of a type

I am trying to find all types that are assignable to a variable of closed type, say ISteering<Foo> and have paremeterless constructor. Finding all types that directly implement(e.g. class A : ISteering<Foo>) it is trivial:

var type = typeof(ISteering<TreeMultiNode>);
var types = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s => s.GetTypes())
            .Where(t => type.IsAssignableFrom(t))
            .Where(t => t.GetConstructor(Type.EmptyTypes) != null);

however I am strugging to find other types that also can be assigned, e.g.

//class DefaultSteering<T> : ISteering<T> where T : FooBase, ...
ISteering<Foo> st = new DefaultSteering<Foo>(); //fine for compiler

my research shows that IsAssignableFrom does not cover most of more complicated cases, typical solution to the problem is using GetGenericTypeDefinition:

type.IsAssignableFrom(t) || t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == type)

however it does not work in my case, no matter what I tried the type DefaultSteering<Foo> is never returned. (probably because my type is closed opposed to open type in similar questions).





Aucun commentaire:

Enregistrer un commentaire