samedi 1 août 2015

Calling Type.GetRuntimeMethod on an interface with a generic method returns null

I am using reflection in one of my C# projects: it is Portable Class Library targeting Windows 8.1 and Windows Phone 8.1.

In that project, I have an interface named IMyInterface that has a method DoSomething with a generic parameter TGenericObject. I also have a class named MyClass. At one point, I need to look up the method DoSomething in the specified interface by reflection. So, I am using the GetRuntimeMethod method from the Type class with the actual parameter's type, which is MyClass in my example.

Please, keep in mind that the example I am providing here is just to highlight the problem I am facing. The reality is that the interface IMyInterface and the class MyClass are in another project.

Here's the deal: I was expecting the GetRuntimeMethod to return the MethodInfo of the DoSomething method, but it did not: null is returned.

Is there something easy that I am missing to find the DoSomething method from the IMyInterface or do I have to get hands dirtier?

public interface IMyInterface
{
    void DoSomething<TGenericObject>(TGenericObject myGenericObject);
}

public class MyClass
{ }

class Program
{
    static void Main(string[] args)
    {
        MyClass myClassInst = new MyClass();

        MethodInfo methodInfo = typeof (IMyInterface).GetRuntimeMethod("DoSomething", new [] { myClassInst.GetType() });
    }
}





Aucun commentaire:

Enregistrer un commentaire