Reputation: 364
Let's say I have interfaces IA and IB:
public interface IA {}
public interface IB : IA {}
Now I want list of classes which implement directly IA, but without those implementing IB and others interfaces that are inherited from IA.
If I have classes Foo and Bar:
public class Foo : IA {}
public class Bar : IB {}
I want my code to return only Foo class. I think I can do it via reflection. I have method that returns list of all classes implementing IA, but now I don't know what to do next.
var types = Assembly.Load("abc").GetTypes();
return types.Where(i => typeof(IA).IsAssignableFrom(i) && i.IsClass);
Upvotes: 0
Views: 708
Reputation: 38767
You could make an extension method to determine this:
public static class TypeExtensions
{
public static bool DirectlyImplements(this Type testType, Type interfaceType)
{
if (!interfaceType.IsInterface || !testType.IsClass || !interfaceType.IsAssignableFrom(testType)) { return false; }
return !testType.GetInterfaces().Any(i => i != interfaceType && interfaceType.IsAssignableFrom(i));
}
}
Basically, it checks if the type implements the interface, but also checks that none of the other interfaces the class implements are assignable to it. It will therefore only return classes that directly implement the interface.
You can use it like this:
var list = types.Where(t => t.DirectlyImplements(typeof(IA))).ToList();
Upvotes: 4