Get a .NET type that declares an interface

Suppose the MyType implements the IMyInterface interface. How do I find the ad type of an interface? For example,

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

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

      

+2


source to share


2 answers


You need to use methods GetInterface

or GetInterfaces

Type

.

For example, you can do this:

Type declaration = typeof(MyType).GetInterface("IMyInterface");
Assert.IsNotNull(declaration)

      

Or you could call GetInterfaces

and view the results until you find it IMyInterface

.



Sources:

Type.GetInterface (string)

Type.GetInterfaces ()

+1


source


Would you come up Type.BaseType

until you reach the level you want?



0


source







All Articles