【发布时间】:2014-10-16 18:19:46
【问题描述】:
我的最终目标是创建一个函数,将方法名称动态传递给 Hangfire 库中的类。
例如,下面是可以工作的非动态代码:
RecurringJob.AddOrUpdate(() => myFunction(), Cron.Hourly)
AddOrUpdate 的第一个参数的类型是Expression<Action>。我的第一步是使用反射来动态插入函数名:
Type thisControllerType = this.GetType();
MethodInfo method = thisControllerType.GetMethod(methodName); //methodName passed as string parameter
RecurringJob.AddOrUpdate(() => method.Invoke(this, null), Cron.Hourly);
当我检查 Hangfire 仪表板时,似乎这个表达式被评估为MethodBase.Invoke。所以我需要帮助动态传入方法名。
这可能足以回答我的问题,但我采取的另一条路径是尝试为参数生成整个表达式。
RecurringJob.AddOrUpdate(CreateCallExpression(method), Cron.Hourly);
public Expression<Action> CreateCallExpression(MethodInfo method)
{
//trying to pass in zero argument parameter, not sure if this syntax is correct
var parameter = System.Linq.Expressions.Expression.Parameter(typeof (Array));
return System.Linq.Expressions.Expression.Lambda<Action>(System.Linq.Expressions.Expression.Call(method, parameter));
}
在这种情况下,我收到异常 {“静态方法需要空实例,非静态方法需要非空实例。\r\n参数名称:方法”}。我正在努力,但不确定这是否是我应该走的路。我整天都在做这个,所以我希望有人可以帮助我加快学习速度。
【问题讨论】:
-
是的,我会使用 Expression.Call。不过,这个错误几乎是不言自明的。如果是静态方法,则返回 Expression.Call(method, null)。
-
对不起,我忽略了该方法是非静态的。我不确定纠正此错误的语法。我已经尝试过 method.Invoke()。
-
是Array的实例方法吗?
-
否,控制器类(具有无参数构造函数)。无效 myController.myFunction()
-
好的,那么自然的后续问题就是你为什么要传递一个数组类型的参数。
标签: c# asp.net-mvc reflection lambda hangfire