How do I invoke a MethodInfo that was created from an anonymous method?

2.1k views Asked by At

In a previous question, I asked how to get a MethodInfo from an Action delegate. This Action delegate was created anonymously (from a Lambda). The problem I'm having now is that I can't invoke the MethodInfo, because it requires an object to which the MethodInfo belongs. In this case, since the delegates are anonymous, there is no owner. I am getting the following exception:

System.Reflection.TargetException : Object does not match target type.

The framework I'm working with (NUnit) requires that I use Reflection to execute, so I have to play within the walls provided. I really don't want to resort to using Emit to create dynamic assemblies/modules/types/methods just to execute a delegate I already have.

Thanks.

2

There are 2 answers

1
Hans Passant On

You already got the Method property. You'll need the Target property to pass as the 1st argument to MethodInfo.Invoke().

using System;

class Program {
    static void Main(string[] args) {
        var t = new Test();
        Action a = () => t.SomeMethod();
        var method = a.Method;
        method.Invoke(a.Target, null);
    }
}

class Test {
    public void SomeMethod() {
        Console.WriteLine("Hello world");
    }
}
0
Matthei On

It looks like that lambda methods, even when declared in a static context, are defined as instance methods.

Solution:

public static void MyMethodInvoker( MethodInfo method, object[] parameters )
{
    if ( method.IsStatic )
        method.Invoke( null, parameters );
    else
        method.Invoke( Activator.CreateInstance( method.DeclaringType ), parameters );
}