jeudi 18 octobre 2018

How to find all classes that implements a generic abstract class using reflection in C#?

I have a c# class that looks like this

public abstract class Listener<T> where T : Event
{
    public abstract void Handle(T _event);
}

I extend this class something like this

public class SendWelcomeEmail : Listener<UserWasCreated>
{
    public override void Handle(UserWasCreated _event)
    {
        //...
    }
}

I need to use reflection to find all classes that extend the Listener<> base class.

I tried the following

var listeners = AppDomain.CurrentDomain.GetAssemblies()
                         .SelectMany(assembly => assembly.GetTypes())
                         .Where(x => x.IsClass && !x.IsInterface)
                         .Where(listener => !listener.IsAbstract && listener.IsGenericType && listener.GetGenericTypeDefinition() == typeof(Listener<>))
                         .ToList();

But that does not return anything. This condition returns false all the time listener.GetGenericTypeDefinition() == typeof(Listener<>)

How can I correctly find all the classes that extend the Listener<> base class?





Aucun commentaire:

Enregistrer un commentaire