4

我正在尝试将方法名称传递给 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”,但我看到的是 <Main>b__0<Main>b__1. 我只是想知道是否有办法从动作委托中获取目标方法的实际名称?任何帮助表示赞赏。

4

1 回答 1

8

您可以将输入类型更改为an 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

    }

}
于 2013-04-05T20:37:00.547 回答