如何形成表示接口的继承树的树?

问题描述:

我知道如何使用typeof(T).GetInterfaces()获得T的所有接口,但我需要确切的继承树。
是否有可能从现有的反射API以某种方式解决这个问题?如何形成表示接口的继承树的树?

编辑: 让我澄清:

interface Base1 {} 
interface Base2 {} 
interface Foo : Base1 
interface Final : Foo, Base2 

我想形成一个代表最终的层次结构树。
我已经有了NGenerics的依赖,所以用它来实现树并不是问题。

+0

你是什么意思?你能举一个具体的例子吗? – 2010-11-05 01:06:30

+0

@Sam:看到下面的答案 – 2010-11-05 01:26:21

让我们来看看。据我所知,没有BCL的方式只有获得实际上实现的特定类型的接口,但排除任何类型继承的接口。因此,我们将不得不推出自己的:

public static Dictionary<Type, IEnumerable<Type>> GetInterfaceHierarchyMap(this Type type) 
{ 
    List<Type> typeAncestry = new List<Type>(); 
    Type ancestor = type; 
    while(ancestor != null) 
    { 
     typeAncestry.Add(ancestor); 
     ancestor = ancestor.BaseType; 
    } 
    Dictionary<Type, IEnumerable<Type>> interfaceMaps = new Dictionary<Type, IEnumerable<Type>>(); 
    foreach(Type childType in typeAncestry.Reverse<Type>()) 
    { 
     var mappedInterfaces = interfaceMaps.SelectMany(kvp => kvp.Value); 
     var allInterfacesToPoint = childType.GetInterfaces(); 
     interfaceMaps.Add(childType, allInterfacesToPoint.Except(mappedInterfaces)); 
    } 
    return interfaceMaps; 
} 

一步一个时间:

  1. 我们从当前的类型开始,走了BaseType,直到我们达到根类型。
  2. 我们颠倒了这个列表,所以当我们迭代它时,我们首先从根类型开始。
  3. 对于链中的每种类型,我们获得应用于该类型的所有接口并从祖先类型继承,然后我们使用Except来消除之前迭代中已发现的所有接口。

这会将重复的接口要求视为多余 - 即,如果其中一个祖先类型实现了IDisposable,并且您的类型也如此,则只会计算最早的实现。

这种方法的一个假想的结果将是一本字典,看起来像:

[object] - [] 
[BaseBaseClass] - [ISomeInterface] 
[BaseClass] - [IAnotherInterface, IOneMore] 
[ConcreteClass] - [IYetAnother] 
+0

不错。但是如果我只处理接口呢?有关系吗?实际上它确实是因为它没有基本类型。 – 2010-11-05 01:26:01

+0

@ the_drow不知道你的意思。接口不能从任何东西继承,所以没有层次结构。 – 2010-11-05 01:28:00

+0

@Rex M,Interfaces可以从可以创建层次结构的其他接口继承。 – 2010-11-05 01:51:03