gpt4 book ai didi

c# - hangfire,RecurringJob AddOrUpdate 反射调用 c#

转载 作者:行者123 更新时间:2023-11-30 23:21:01 27 4
gpt4 key购买 nike

我这样从 RecurringJob 调用 AddOrUpdate 方法

public override string StartWork()
{
RecurringJob.AddOrUpdate<SomeScenario>(jobEntity.Name, x => x.Execute(jobEntity.Name), cron, TimeZoneInfo.Utc);
}

我需要重写这个方法,以反射调用。我找到了合适的方法重载

  MethodInfo addOrUpdate = typeof(RecurringJob).GetMethods().Where(x => x.Name == "AddOrUpdate" && x.IsGenericMethod && x.IsGenericMethodDefinition).Select(m => new
{
Method = m,
Params = m.GetParameters(),
Args = m.GetGenericArguments()
})
.Where(x => x.Params.Length == 5
&& x.Params[0].ParameterType == typeof(string)
&& x.Params[2].ParameterType == typeof(string)
&& x.Params[3].ParameterType == typeof(TimeZoneInfo)
&& x.Params[4].ParameterType == typeof(string)
)
.Select(x => x.Method).FirstOrDefault();

我在数据库中保存了正确的类型,所以我会这样获取它

Type type = Type.GetType(jobEntity.ScenarioType);
MethodInfo generic = addOrUpdate.MakeGenericMethod(type);

因此,现在我需要使用适当的参数调用此方法。

public static void AddOrUpdate<T>(string recurringJobId, Expression<Action<T>> methodCall, string cronExpression, TimeZoneInfo timeZone = null, string queue = "default")

问题:我不知道如何生成Expression<Action<T>>在这种情况下,调用 generic.Invoke(this, new object[] { jobEntity.Name, Expression<Action<T>>, cron, TimeZoneInfo.Utc, null });

非常感谢您的帮助。

最佳答案

 MethodInfo generic = addOrUpdate.MakeGenericMethod(scenarioType);
ParameterExpression param = Expression.Parameter(scenarioType, "x");
ConstantExpression someValue = Expression.Constant(jobName, typeof(string));
MethodCallExpression methodCall = Expression.Call(param, scenarioType.GetMethod("Execute", new Type[] { typeof(string) }), someValue);
LambdaExpression expre = Expression.Lambda(methodCall, new ParameterExpression[] { param });
generic.Invoke(self, new object[] { jobName, expre, cron, TimeZoneInfo.Utc, null });

有效:|

关于c# - hangfire,RecurringJob AddOrUpdate 反射调用 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39505845/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com