【问题标题】:How to form a tree that represents the inheritance tree of an interface?如何形成表示接口继承树的树?
【发布时间】:2010-11-05 00:46:47
【问题描述】:

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

编辑: 请允许我澄清一下:

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

我想形成一棵代表 Final 层次结构的树。
我已经依赖于 NGenerics,因此将它用于树实现不是问题。

【问题讨论】:

  • 什么意思?能举个具体的例子吗?

标签: c# reflection interface


【解决方案1】:

让我们看看。据我所知,没有 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]

【讨论】:

  • 不错。但是如果我只处理接口呢?有关系吗?实际上是因为它没有基类型。
  • @the_drow 不确定您的意思。接口不能从任何东西继承,所以没有层次结构。
  • @Rex M,接口可以从其他可以创建层次结构的接口继承。
  • @Sam 接口可以需要其他接口。这与继承不同。
  • @Rex M,实际上,文档专门使用了术语继承。 “一个接口本身可以继承多个接口” msdn.microsoft.com/en-us/library/ms173156.aspx
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-16
  • 2018-12-28
  • 2016-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多