views:

108

answers:

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.

+1  A: 

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
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