表达式<Action <T >> methodCall

blu*_*uee 4 c# generics lambda

如何在Enqueue中运行methodCall?

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

通话方式:

Enqueue<QueueController>(x => x.SomeMethod("param1", "param2"));
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 5

为了实现这一点,您需要一个实例,T以便您可以在此实例上调用该方法.您还Enqueue必须根据您的签名返回一个字符串.所以:

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);
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我已经为T参数添加了一个通用约束,以便能够获取实例.如果您能够从其他地方提供此实例,那么您可以这样做.


更新:

根据评论部分的要求,这里是如何使用Action<T>:

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";
}
Run Code Online (Sandbox Code Playgroud)