简体   繁体   中英

Get all c# Types that implements an interface first but no derived classes

related to Getting all types that implement an interface we can easily get all Types in the Assembly that implements a specific interface.

Example:

interface IFace
{
}

class Face : IFace
{
}

class TwoFace : Face
{
}

For this structure, we will find both classes via reflection, ie all classes that are derived from the first implementation too, using

GetTypes().Where(
  type => type.GetInterfaces().Contains(typeof(IFace))
)

So the question is: how can I restrict the result to the base class that initially implements the interface?! In this example: only class type Face is relevant.

Firstly, I'd use Type.IsAssignableFrom rather than GetInterfaces , but then all you need to do is exclude types whose parent type is already in the set:

var allClasses = types.Where(type => typeof(IFace).IsAssignableFrom(type))
                      .ToList(); // Or use a HashSet, for better Contains perf.
var firstImplementations = allClasses
      .Except(allClasses.Where(t => allClasses.Contains(t.BaseType)));

Or as noted in comments, equivalently:

var firstImplementations = allClasses.Where(t => !allClasses.Contains(t.BaseType));

Note that this will not return a class which derives from a class which implements an interface, but reimplements it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM