替换 if 语句的 Lambda 表达式

Lambda expression to replace if statement

我想删除带有 lambda 表达式的 if 语句以避免重复

if (string.IsNullOrEmpty(ConfigurationSettings.Hour.ToString()))
{
       service.ScheduleQuartzJob(q =>
       q.WithJob(() =>
       JobBuilder.Create<ServiceJob>().Build())
       .AddTrigger(() => TriggerBuilder.Create()
       .WithCronSchedule(ConfigurationSettings.RunAtSchedule)
       .Build()));
}
else
{
       service.ScheduleQuartzJob(q =>
       q.WithJob(() =>
       JobBuilder.Create<ServiceJob>().Build())
       .AddTrigger(() => TriggerBuilder.Create()
       .WithSchedule(CronScheduleBuilder
       .DailyAtHourAndMinute(ConfigurationSettings.Hour,
       ConfigurationSettings.RunAtMinute))
       .Build()));
}

我如何重构它以使用 lambda 替换 if 语句?

非常感谢

加里

不清楚用 lambda 替换它是什么意思。但我认为这可能 接近 你所追求的:

var builder = TriggerBuilder.Create();
var schedule = string.IsNullOrEmpty(ConfigurationSettings.Hour.ToString()) 
    ? builder.WithCronSchedule(ConfigurationSettings.RunAtSchedule)
    : builder.WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(ConfigurationSettings.Hour, ConfigurationSettings.RunAtMinute));

service.ScheduleQuartzJob(
  q => q.WithJob(
    () => JobBuilder.Create<ServiceJob>().Build())
                    .AddTrigger(() => schedule.Build())
  ) 
);

我不熟悉 Quartz,但我假设以上内容应该有效。如果你需要在 lambda 中传递它,你可以这样做:

service.ScheduleQuartzJob(
  q => q.WithJob(
    () => JobBuilder.Create<ServiceJob>().Build())
                    .AddTrigger(
                          () => (string.IsNullOrEmpty(ConfigurationSettings.Hour.ToString()) 
                              ? TriggerBuilder.Create().WithCronSchedule(ConfigurationSettings.RunAtSchedule)
                              : TriggerBuilder.Create().WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(ConfigurationSettings.Hour, ConfigurationSettings.RunAtMinute))
                            ).Build()
             )
      ) 
);

注意:我认为我匹配了所有的右括号,但有可能我在手机上输入时遗漏了一个。