Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression<Action<T>> methodCall

How do I run methodCall inside Enqueue?

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

Calling method:

Enqueue<QueueController>(x => x.SomeMethod("param1", "param2"));
like image 459
bluee Avatar asked Mar 18 '23 00:03

bluee


1 Answers

In order to achieve that you will need an instance of T so that you can invoke the method on this instance. Also your Enqueue must 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 have added a generic constraint to the T parameter in order to be able to get an instance. If you are able to provide this instance from somewhere else then you could do so.


UPDATE:

As requested in the comments section here's 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";
}
like image 151
Darin Dimitrov Avatar answered Mar 28 '23 21:03

Darin Dimitrov