我希望我理解正确的问题:)
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);
}
如可以看出,该代码假定类实现IParent(否则 - 错误...)。
试验样品:
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
载入第一类型实现接口:
public Type FindImplementor<T>()
{
return AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes())
.FirstOrDefault(type => type.GetInterfaces().Contains(typeof(T)));
}
我假定该组件被加载到应用程序域和码搜索一个实施者的地方。如果只有单个程序集很有趣,那么你只能得到这个程序集类型(就像在Guillaume的答案中一样)
C#支持接口的多重继承。假设有两个从IParent继承的接口:IChild1和IChild2。如果一个类实现IChild1和IChild2,会发生什么? – 2009-11-12 15:55:47
旧的多重继承钻石。在我的情况下,我没有使用该功能。我实现多个接口的所有类都实现了没有共同祖先的接口。 – 2009-11-12 16:01:25
即使没有“钻石”,您仍然必须遍历整个接口继承树,才能找到IParent。递归函数让人想起遍历树来寻找某物。 – 2009-11-12 16:19:42