我希望我理解正確的問題:)
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