Creating a collection of all classes that inherit

2019-03-31 07:59发布

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;

4条回答
该账号已被封号
2楼-- · 2019-03-31 08:44

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

查看更多
Melony?
3楼-- · 2019-03-31 08:46

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.

查看更多
Emotional °昔
5楼-- · 2019-03-31 08:52

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.

查看更多
登录 后发表回答