How can I create a MethodInfo from an Action delegate

9k views Asked by At

I am trying to develop an NUnit addin that dynamically adds test methods to a suite from an object that contains a list of Action delegates. The problem is that NUnit appears to be leaning heavily on reflection to get the job done. Consequently, it looks like there's no simple way to add my Actions directly to the suite.

I must, instead, add MethodInfo objects. This would normally work, but the Action delegates are anonymous, so I would have to build the types and methods to accomplish this. I need to find an easier way to do this, without resorting to using Emit. Does anyone know how to easily create MethodInfo instances from Action delegates?

3

There are 3 answers

0
Fede On BEST ANSWER

Have you tried Action's Method property? I mean something like:

MethodInfo GetMI(Action a)
{
    return a.Method;
}
2
Ben Voigt On
MethodInvoker CvtActionToMI(Action d)
{
   MethodInvoker converted = delegate { d(); };
   return converted;
}

Sorry, not what you wanted.

Note that all delegates are multicast, so there isn't guaranteed to be a unique MethodInfo. This will get you all of them:

MethodInfo[] CvtActionToMIArray(Action d)
{
   if (d == null) return new MethodInfo[0];
   Delegate[] targets = d.GetInvocationList();
   MethodInfo[] converted = new MethodInfo[targets.Length];
   for( int i = 0; i < targets.Length; ++i ) converted[i] = targets[i].Method;
   return converted;
}

You're losing the information about the target objects though (uncurrying the delegate), so I don't expect NUnit to be able to successfully call anything afterwards.

1
Thomas Levesque On

You don't need to "create" a MethodInfo, you can just retrieve it from the delegate :

Action action = () => Console.WriteLine("Hello world !");
MethodInfo method = action.Method