I hope I understood the question correctly :)
ClosestAncestor
public Type ClosestAncestor<IParent, Class>()
{
return ClosestAncestor<IParent>(typeof(Class));
}
public Type ClosestAncestor<IParent>(Type typeOfClass)
{
var baseType = typeOfClass.BaseType;
if(typeOfClass.GetInterfaces().Contains(typeof(IParent)) &&
! baseType.GetInterfaces().Contains(typeof(IParent)))
{
return typeOfClass;
}
return ClosestAncestor<IParent>(baseType);
}
As it can be seen, the code assumes Class implements IParent (otherwise - bug...).
Test sample:
public interface I {}
public class A {}
public class B : A, I {}
public class C : B {}
[Test]
public void ClosestAncestorTest()
{
Type closestAncestor = ClosestAncestor<I,C>();
Assert.AreEqual(typeof(B), closestAncestor);
}
FindImplementor
Loading first type that implements an interface:
public Type FindImplementor<T>()
{
return AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes())
.FirstOrDefault(type => type.GetInterfaces().Contains(typeof(T)));
}
I assumed the assembly is loaded to the App Domain and the code searches all over the place for an implementer. If only single assembly is interesting, you can get only this assembly types (Like in Guillaume's answer)