Get all classes that implement a certain abstract

2019-02-24 13:29发布

问题:

I'm trying to get all classes that implement a certain abstract class. I'm trying to do that with the following code:

var type = typeof(BaseViewComponent);
var types = Assembly
    .GetEntryAssembly()
    .GetReferencedAssemblies()
    .Select(Assembly.Load)
    .SelectMany(s => s.GetTypes())
    .Where(p => type.IsAssignableFrom(p));

But thus far I'm only able to get the abstract class it self. Not any class that implements that base class.

What do I have to change to get all the classes that implement this abstract base class?

回答1:

using System.Reflection;
using Microsoft.Extensions.DependencyModel;
var asmNames = DependencyContext.Default.GetDefaultAssemblyNames();
var type = typeof(BaseViewComponent);

var allTypes = asmNames.Select(Assembly.Load)
    .SelectMany(t => t.GetTypes())
    .Where(p => p.GetTypeInfo().IsSubclassOf(type));