0

How do I get the arguments 1 and 2 when I only have the Action delegate?

public class Program
{
    public static void Main(string[] args)
    {
        Action act = () => new Program().Test(1, 2);
    }

    public void Test(int arg1, int arg2)
    {
    }
}
Maksim Simkin
  • 9,381
  • 4
  • 38
  • 48
Martin
  • 325
  • 3
  • 12

3 Answers3

4

You cannot. To do that, you would need an Expression<Action> (See Expression in the MSDN) and you cannot convert from an Action to an Expression<Action>, only the other direction.

Further reading

Community
  • 1
  • 1
nvoigt
  • 68,786
  • 25
  • 88
  • 134
1

Do you mean something like this:

Action<int,int> act = (a,b) => new Program().Test(a,b);

It could be called than as act(1,2);

Maksim Simkin
  • 9,381
  • 4
  • 38
  • 48
0

It can't be done using an Action, but a lambda expression can also be treated as an Expression<Action> and then it becomes possible.

Note that the code below only works for this kind of expression: it uses the knowledge that we have a method call and that we use constants as parameters.

public class Program
{
    public static void Main(string[] args)
    {
        var values = GetParams(() => Test(1, 2));
        foreach (var v in values)
            System.Diagnostics.Debug.Print(v.ToString());
    }

    private object[] GetParams<T>(Expression<Func<T>> expr)
    {
        var body = (MethodCallExpression)expr.Body;
        var args = body.Arguments;
        return args.Select(p => ((ConstantExpression)p).Value).ToArray();
    }

    public int Test(int arg1, int arg2)
    {
        return arg1 + arg2;
    }
}
Peter B
  • 21,067
  • 5
  • 28
  • 63