开发者

How can I create a MethodInfo from an Action delegate

开发者 https://www.devze.com 2022-12-26 04:59 出处:网络
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 r

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 t开发者_开发知识库he 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?


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

MethodInfo GetMI(Action a)
{
    return a.Method;
}


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消