mercredi 4 janvier 2017

Using relection to find a type's implementation of an interface method

Consider this example:

public interface MyInterface
{
    string GetFoo();
}

public class MyClass : MyInterface
{
    public string GetFoo()
    {
        return "Foo";
    }
}

Now say I have an instance of a MethodInfo object that represents the abstract interface method:

MethodInfo abstractMethod = typeof(MyInterface).GetMethod("GetFoo");

I would like to obtain a MethodInfo instance for the exact method a given type uses to implement the interface method.

For an abstract/virtual class (not interface) method, this can be done:

MethodInfo implementation = typeof(MyClass).GetMethods().Single(m => m.GetBaseDefinition() == abstractMethod);

How can I do this for an interface method? Checking method names is not sufficient in case the type implicitly declares the method.





Aucun commentaire:

Enregistrer un commentaire