1

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.

Community
  • 1
  • 1
Michael Meadows
  • 27,796
  • 4
  • 47
  • 63

2 Answers2

3

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");
    }
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • That didn't work for me. I suspect there must be more going on in the innards of NUnit. I found a workaround, however kludgey it may be. They made all the methods virtual, so I pass it the MethodInfo, but just override the method where it's called, and call the Action directly. – Michael Meadows Apr 08 '10 at 10:23
0

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 );
}
Matthei
  • 98
  • 7