How can I create a MethodInfo from an Action delegate

倖福魔咒の 提交于 2019-12-08 15:40:42

问题


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?


回答1:


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

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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/2576640/how-can-i-create-a-methodinfo-from-an-action-delegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!