Getting method name from an Action delegate
Asked Answered
U

1

6

I'm trying to get the method name passed into an Action delegate. This is what I have:

private static void DoAction(params Action<Group>[] actions)
{
    foreach (Action<Group> action in actions)
    {
        Console.WriteLine(action.Method.Name);
    }
}

And in main, this is how it gets called:

DoAction(y => y.DoBar(), z => z.DoFoo());

After the execution of DoAction() method I was hoping to see "DoFoo" and "DoBar" on the screen, but it instead I see <Main>b__0 and <Main>b__1. I was just wondering if there's a way to get the actual name of the target method from an action delegate? Any help is appreciated.

Uraeus answered 5/4, 2013 at 20:22 Comment(0)
H
9

You can change the input type to an Expression and then see if the expression is a method call:

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

    }

}
Hylophagous answered 5/4, 2013 at 20:37 Comment(2)
How can I invoke the method now? action() doesn't work. Expression.Invoke() also requires arguments for the method. Assuming Foo() and Bar() methods both take arguments, how can specify the arguments in main and invoke it in DoAction()?Uraeus
@programmer93 use Expression.Compile() to convert it to an Action. See my updated answer.Hylophagous

© 2022 - 2024 — McMap. All rights reserved.