vendredi 22 avril 2016

Get derived class via reflection? [duplicate]

This question already has an answer here:

I have 2 dlls, one with an interface and another that actually uses the interface. I can call the 2nd dll using reflection, but I wanted to know if I can get more information about it using the interface.

I have something like...

// the interface dll
namespace Mynamespace{
  public interface Interface1
  {
    int Add( int a, int b);
  }
}

and another interface in the same dll...
note that it is derived from the first one.

namespace Mynamespace{
  public interface Interface2 : Interface1
  {
    int Sub( int a, int b);
  }
}

I then call a method using reflection

// get the 2 interfaces
var asm = Assembly.LoadFile( dllInterfacePath);
var type1 = asm.GetType("Mynamespace.Interface1");
var type2 = asm.GetType("Mynamespace.Interface2");

// get the main class
var asmDll = Assembly.LoadFile( dllPath);
var type = asmDll.GetType("MyMS.SomeClass");

// create an instance
var instance = Activator.CreateInstance( type, null );

Now my question is how can I tell if the instance created is derived off Interface2 or Interface1, I could look for method "Sub(...)" and if it is not present then I know it is of type Interface1.

But I was wondering if there was a better function to dynamically achieve this?





Aucun commentaire:

Enregistrer un commentaire