获取.NET类型声明接口

时间:2009-08-20 07:18:41

标签: .net reflection

假设MyType类型实现接口IMyInterface。如何查找声明界面的类型?例如,

class UnitTest 
{
  MyTypeBase : IMyInterface  { }
  MyType : MyTypeBase  { }

  void Test() {
    Type declaration = FindDeclaration(typeof(MyType), typeof(IMyInterface));
    Assert.AreEqual(typeof(MyTypeBase), declaration) 
  }

2 个答案:

答案 0 :(得分:1)

您需要使用GetInterface的{​​{1}}或GetInterfaces方法。

例如,你可以这样做:

Type

或者您可以致电Type declaration = typeof(MyType).GetInterface("IMyInterface"); Assert.IsNotNull(declaration) 并循环搜索结果,直至找到GetInterfaces

来源:

Type.GetInterface(string)

Type.GetInterfaces()

答案 1 :(得分:0)

你会走Type.BaseType,直到达到你想要的水平?

相关问题