Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Parameters from Action<T>

How do I get the parameters passed into an Action<T> ? The code example should highlight what I'm trying to achieve. Sorry that it's a little bit long.

public class Program
{
    public static void Main(string[] args)
    {
        var foo = new Foo();
        foo.GetParams(x => x.Bar(7, "hello"));
    }
}

public class Foo
{
    public void Bar(int val, string thing) { }
}

public static class Ex
{
    public static object[] GetParams<T>(this T obj, Action<T> action)
    {
        // Return new object[] { 7, "hello" }
    }
}

The only options that look vaguely useful are GetInvocationList(), Method and Target. But none of them seem to contain the data I'm after (I think it's because of the way I've declared the Action). Thanks

EDIT: It's not the types I want, it's the actual values - as noted in the commented bit of code.

like image 786
RichK Avatar asked Dec 05 '10 21:12

RichK


People also ask

What are action parameters?

Action parameters enable you specify parameters that are available for all steps contained in the action. Action parameters are stored with the action and are maintained to all calls to the action. You can provide the action parameter value from any of the following: A test parameter.

What is action t used for in an application?

You can use the Action<T> delegate to pass a method as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate.

How do you pass an action in a method?

Use Action Delegate to Pass a Method as a Parameter in C# We can also use the built-in delegate Action to pass a method as a parameter. The correct syntax to use this delegate is as follows. public delegate void Action<in T>(T obj); The built-in delegate Action can have 16 parameters as input.


1 Answers

To do that, it should actually be an Expression<Action<T>>. Then it is a case of decomposing the expression. Fortunately I have all the code for that over in protobuf-net, here - in particular ResolveMethod, which returns the values in the out array (after walking any captured variables, etc).

After making ResolveMethod public (and removing everything above ResolveMethod), the code is just:

public static object[] GetParams<T>(this T obj, Expression<Action<T>> action)
{
    ProtoClientExtensions.ResolveMethod<T>(
        action, out Action ignoreThis, out object[] args);
    return args;
}
like image 185
Marc Gravell Avatar answered Oct 04 '22 11:10

Marc Gravell