bluee
bluee

Reputation: 1027

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"));

Upvotes: 5

Views: 10243

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

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";
}

Upvotes: 7

Related Questions