我正在尝试将方法名称传递给Action委托。这就是我所拥有的:
private static void DoAction(params Action<Group>[] actions)
{
foreach (Action<Group> action in actions)
{
Console.WriteLine(action.Method.Name);
}
}
总的来说,这就是它被调用的方式:
DoAction(y => y.DoBar(), z => z.DoFoo());
执行DoAction()方法后,我希望在屏幕上看到“DoFoo”和“DoBar”,但我看到&lt; Main>b__0
和<Main>b__1
。我只是想知道是否有办法从动作委托中获取目标方法的实际名称?任何帮助表示赞赏。
答案 0 :(得分:8)
您可以将输入类型更改为Expression
,然后查看表达式是否为方法调用:
private static void DoAction(params Expression<Action<Group>>[] actions)
{
foreach (var exp in actions)
{
var method = exp.Body as MethodCallExpression;
if(method != null)
Console.WriteLine(method.Method.Name);
// similar method for properties
var member = exp.Body as MemberExpression;
if (member != null)
Console.WriteLine(member.Member);
// execute the Action
Action<Group> act = exp.Compile();
Group g = new Group(); // create a Group to act on
act(g); // perform the action
}
}