How to capture assembly from classes that inherit from a single class

3

I have numerous classes.

All inherit from a single class

public abstract class ClasseBase 
{
   public int Id {get;set;}
}

and other classes:

public class Teste1 : ClasseBase{ } public class Teste2 : ClasseBase { }

You would need to capture all class assembly inheritance classes

How could I do this?

    
asked by anonymous 04.12.2014 / 18:56

2 answers

3

Using LINQ you can do this:

var lista = (from arquivo in AppDomain.CurrentDomain.GetAssemblies()
                   from tipo in arquivo.GetTypes()
                   where typeof(ClasseBase).IsAssignableFrom(tipo)
                   select tipo).ToArray();

See working on dotNetFiddle .

With LINQ using lambda expressions (created by AP Rod):

var teste = AppDomain.CurrentDomain.GetAssemblies().Select(x => x.GetTypes()) 
                .SelectMany(x => x).Where(x => typeof(ClasseBase).IsAssignableFrom(x))
                .ToArray();

No LINQ:

foreach(var arquivo in AppDomain.CurrentDomain.GetAssemblies()) {
    foreach(var tipo in arquivo.GetTypes()) {
        if (typeof(ClasseBase).IsAssignableFrom(tipo)) {
            Console.WriteLine(tipo);
        }
    }
}

See running on dotNetFiddle .

    
04.12.2014 / 19:03
3

So:

Type[] types = Assembly.GetExecutingAssembly().GetTypes();
foreach (Type type in types)
{
    if (type.IsSubclassOf(typeof(ClasseBase)))
    {
        // Faça aqui o que você precisa. A classe encontrada está em "type".
    }
}
    
04.12.2014 / 18:58