题
这 系统类型 类提供了一个 获取接口() 方法“获取当前 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)。A 查找接口还提供了 () 方法,允许您使用您选择的谓词来过滤上述接口。
我当前的实现如下。它是 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());
}
提前致谢
解决方案
我不认为你会发现一个简单的解决这个。你的问题是,在年底,Foo
实际实现的所有接口的,不论其内部的继承层次。如果您在使用反汇编或一些类似的工具检查Foo
这变得明显。考虑下面的代码:
interface IFirst { }
interface ISecond : IFirst { }
class Concrete : ISecond { }
将所得的IL代码(从倾倒ILDASM):
.class private auto ansi beforefieldinit MyNamespace.Concrete
extends [mscorlib]System.Object
implements MyNamespace.ISecond,
MyNamespace.IFirst
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method Concrete::.ctor
} // end of class MyNamespace.Concrete
可以看到,在这个层面上存在Concrete
和两个接口之间的关系没有任何区别。
不隶属于 StackOverflow