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

Asked

Viewed 103 times

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 { }

It would need to capture all assemblys of the classes they inherit from Classebase

How could I do that ?

2 answers

3

Thus:

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".
    }
}

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();

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

With LINQ using expressions lambda (set up by AP Rod):

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

Linless:

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

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • that’s exactly what I wanted, thank you, but I’m trying to adapt without using LINQ, but still, thank you.

  • Do you have Resharper? It helps do this. I haven’t worked with C# for some time so I don’t have all the tools to make the job easier. Of course you can do manual too, it’s not complicated.

  • my Resharp expired today, but I’ll try to do it manually anyway, thank you

  • Done in the hand real quick.

  • I also did in lambda, adds in your answer, which is more complete, for those who someday come looking, code: var test = Appdomain.CurrentDomain.Getassemblies() . Select(x => x.Gettypes()) . Selectmany(x => x) . Where(x => typeof(Classebase).Isassignablefrom(x)). Toarray();

Browser other questions tagged

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