System.Type类提供了一个GetInterfaces () 方法,“获取当前Type 实现或继承的所有接口” 。问题是“GetInterfaces 方法不会以特定顺序返回接口,例如字母顺序或声明顺序。您的代码不能依赖于返回接口的顺序,因为该顺序会有所不同”。然而,在我的情况下,我只需要隔离和公开(通过 WCF)接口层次结构的叶接口,即不被该层次结构中的其他接口继承的接口。例如,考虑以下层次结构
interface IA { }
interface IB : IA { }
interface IC : IB { }
interface ID : IB { }
interface IE : IA { }
class Foo : IC, IE {}
Foo 的叶子接口是 IC 和 IE,而 GetInterfaces() 将返回所有 5 个接口(IA..IE)。还提供了FindInterfaces () 方法,允许您使用您选择的谓词过滤上述接口。
我目前的实现如下。它是 O(n^2),其中 n 是该类型实现的接口数。我想知道是否有更优雅和/或更有效的方法。
private Type[] GetLeafInterfaces(Type type)
{
return type.FindInterfaces((candidateIfc, allIfcs) =>
{
foreach (Type ifc in (Type[])allIfcs)
{
if (candidateIfc != ifc && candidateIfc.IsAssignableFrom(ifc))
return false;
}
return true;
}
,type.GetInterfaces());
}
提前致谢