使用反射将类作为输入传递

时间:2014-08-06 18:08:43

标签: c# class reflection quartz-scheduler

我有一个创建Quartz作业的函数,并按如下方式返回调度程序:

public IScheduler ScheduleJob<T>(string jobName, string jobGroup, string triggerName, string triggerGroup, bool rerun, string cronSchedule = "default", string startTime = "default") where T : IJob
    {
        var scheduler = StdSchedulerFactory.GetDefaultScheduler();
        var jobKey = new JobKey(jobName, jobGroup);
        var job = JobBuilder.Create<T>()
                .WithIdentity(jobKey)
                .StoreDurably()
                .Build();
        var trigger = cronSchedule != "default" ? QuartzCreateCronTrigger(triggerName, triggerGroup, cronSchedule, rerun, startTime) : QuartzCreateTrigger(triggerName, triggerGroup);

        scheduler.ScheduleJob(job, trigger);
        return scheduler;
    }

我有几个类,每个类都包含一个要安排和运行的作业。我有以下函数,它取一个类的名称和一些其他信息,然后安排作业。该函数调用上述函数。

public static void CreateScheduler(bool rerun, string jobName, string jobType, string schedule, string startTime)
{
    var job =  (IJob) Activator.CreateInstance(Type.GetType("MyProject.Jobs." + jobType + "." + jobName + ", " + Assembly.GetExecutingAssembly().FullName.ToString()));
    var scheduler =
        new QuartzConstraints().ScheduleJob<job>(
            jobName,
            jobType,
            jobName + "Trigger",
            jobType,
            rerun,
            schedule,
            startTime);
    scheduler.Start();
}

问题是我在new QuartzConstraints().ScheduleJob<job>(...)中收到错误,说“无法解析符号'作业'”。 ScheduleJob<T>应该T类型为IJob,这是正确的。我不确定我在这里做错了什么。

编辑:

当我专门定义每个类时,代码可以工作,但是我想编写一个方法(CreateScheduler),它可以适用于任何类。例如,这是有效的(ThisIsAJobClass是一个实现IJob的类):

 var scheduler =
     new QuartzConstraints().ScheduleJob<ThisIsAJobClass>(
        "ThisIsAJobClass",
        "JobGroup1",
        "ThisIsAJobClassTrigger",
        "JobGroup1",
        true,
        "0 0/1 * ? * MON-FRI",
        "6:20 AM");
scheduler.Start();

1 个答案:

答案 0 :(得分:2)

您应该写new QuartzConstrainst().ScheduleJob<IJob>,而不是.ScheduleJob<job>

job不是一种类型,你自己说ScheduleJob<T> should have T as type IJob

如果您想将var job传递给ScheduleJob,那么您应该像这样定义SheduleJob

public IScheduler ScheduleJob<T>(
    T job, // <-- add this
    string jobName,
    string jobGroup,
    string triggerName,
    string triggerGroup,
    bool rerun,
    string cronSchedule = "default",
    string startTime = "default") where T : IJob
{
    // code
}

然后将job传递给此函数,如下所示:

public static void CreateScheduler(bool rerun, string jobName, string jobType, string schedule, string startTime)
{
    var job =  (IJob) Activator.CreateInstance(Type.GetType("MyProject.Jobs." + jobType + "." + jobName + ", " + Assembly.GetExecutingAssembly().FullName.ToString()));
    var scheduler =
        new QuartzConstraints().ScheduleJob<IJob>(
            job // <-- add this
            jobName,
            jobType,
            jobName + "Trigger",
            jobType,
            rerun,
            schedule,
            startTime);
    scheduler.Start();
}