Expression <Action <T>> methodCall

How to run the Call method inside Enqueue?

public static string Enqueue<T>(System.Linq.Expressions.Expression<Action<T>> methodCall)
{
   // How to run methodCall with it parameters? 
}

Call Method:

Enqueue<QueueController>(x => x.SomeMethod("param1", "param2"));
+4
source share
1 answer

To do this, you need an instance Tso that you can call the method on that instance. Also your Enqueueshould return a string according to your signature. So:

public static string Enqueue<T>(System.Linq.Expressions.Expression<Func<T, string>> methodCall)
    where T: new()
{
    T t = new T();
    Func<T, string> action = methodCall.Compile();
    return action(t);
}

As you can see, I added a general constraint to the parameter Tin order to be able to get an instance. If you can provide this instance from another place, you can do it.


UPDATE:

As stated in the comments section here, how to use Action<T>instead:

public static string Enqueue<T>(System.Linq.Expressions.Expression<Action<T>> methodCall)
    where T: new()
{
    T t = new T();
    Action<T> action = methodCall.Compile();
    action(t);

    return "WHATEVER";
}
+5
source

All Articles