Create a collection of all classes that inherit from IBlahblah

Using reflection (I guess?), Is it possible to create a method that returns a collection of all objects that inherit from the IBlahblah interface?

public interface IBlahblah;
+3
source share
4 answers

Assuming you have an assembly (or list of assemblies) to search for, you can get a set of types that implement the interface:

var blahs = assembly.GetTypes()
                    .Where(t => typeof(IBlahblah).IsAssignableFrom(t));

You cannot get a collection of "live objects" that implement the interface, although at least not using the debug / profiling API or something like that.

+11
source

, , post LINQ.

+2
source

Yes it is possible:

    var result = new List<Type>();
    foreach(var assembly in AppDomain.CurrentDomain.GetAssemblies())
        foreach(var type in assembly.GetTypes())
            if (typeof(IBlahblah).IsAssignableFrom(type))
                result.Add(type);

And that includes types outside the current assembly.

+2
source

Source: https://habr.com/ru/post/1720465/


All Articles