Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

An answer on " Implementations of interface through Reflection " shows how to get all implementations of an interface. However, given a generic interface, IInterface<T>, the following doesn't work:

var types = TypesImplementingInterface(typeof(IInterface<>))

Can anyone explain how I can modify that method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
599 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use something like this:

public static bool DoesTypeSupportInterface(Type type, Type inter)
{
    if(inter.IsAssignableFrom(type))
        return true;
    if(type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == inter))
        return true;
    return false;
}

public static IEnumerable<Type> TypesImplementingInterface(Type desiredType)
{
    return AppDomain
        .CurrentDomain
        .GetAssemblies()
        .SelectMany(assembly => assembly.GetTypes())
        .Where(type => DoesTypeSupportInterface(type, desiredType));

}

It can throw a TypeLoadException though but that's a problem already present in the original code. For example in LINQPad it doesn't work because some libraries can't be loaded.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...