2016-09-15 24 views
0

我打電話AddOrUpdate方法從RecurringJob像遲髮型,RecurringJob AddOrUpdate反射調用C#

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

所以,現在我需要調用此方法prooper參數。

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

謝謝了很多,任何幫助。

回答

0
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 }); 

它的工作原理: