Creating a collection of all classes that inherit

2019-03-31 08:22发布

问题:

Using reflection (i'm guessing?), is it possible to create a method that will return a collection of all objects that inherit from an interface named IBlahblah?

public interface IBlahblah;

回答1:

Assuming you have an assembly (or a list of assemblies) to look in, you can get a collection of types which implement an interface:

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

You can't get a collection of "live objects" implementing the interface though - at least not without using the debugging/profiling API or something similar.



回答2:

Do you mean something like this ?



回答3:

Yes, this is possible, this other stack overflow post gives the solution with LINQ.



回答4:

Yes this 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 this includes the types outside of the current assembly.