Get all classes that implement a generic interface

Asked

Viewed 324 times

8

I have an interface similar to this:

public interface InterfaceA<T>
{
   T Exemplo();
}

And other classes implement it.

public class ExemploA : InterfaceA<Int32>
{
    Int32 Exemplo();
}

public class ExemploB : InterfaceA<String>
{
    String Exemplo();
}

Researching found this reply on Soen, but I cannot get the type of the interface without the generics.

var type = typeof(InterfaceA); //erro

Does anyone know how I can get the type of the classes ExemploA, ExemploB, searching for the InterfaceA, within a given assembly?

  • You want to get all classes that implement InterfaceA. Right?

  • That’s right, no matter what InterfaceA<Int32> or InterfaceA<String>, list all that implement InterfaceA

  • 1

    @Marcogiovanni did one more edit making the Linq search by type Generic InterfaceA<> is a good one too ...

1 answer

5


With to make a search for name:

var types = System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
                .Where(p => p.GetInterfaces().Where(c => c.Name.Contains("InterfaceA"))
                             .Any())                
                .ToList();

or

The search for the guy generic of Interface:

var types = System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
                .Where(p => p.GetInterfaces()
                             .Where(c => c.IsGenericType &&
                                    c.GetGenericTypeDefinition() == typeof(InterfaceA<>))
                                     .Any())                
                .ToList();

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.