0

我的项目中的类库中有许多不同的类。我正在使用 Quartz.NET(一个调度系统)来调度和加载作业,实际的作业执行是在这些类库中完成的。我计划有很多类型的作业类型,每一种都会有自己的类在类库中执行。

我遇到的一个问题是我不能在这些类中嵌套方法。例如,这是我的课:

public class FTPtoFTP : IJob
{
    private static ILog _log = LogManager.GetLogger(typeof(HTTPtoFTP));

    public FTPtoFTP()
    {

    }

    public virtual void Execute(JobExecutionContext context)
    {          
        //Code that executes, the variable context allows me to access the job information
    }
}

如果我尝试将一个方法放在类的执行部分,例如......

 string[] GetFileList()
 { 
    //Code for getting file list
 }

它希望在我的 GetFileList 开始之前结束执行方法,并且也不让我访问我需要的上下文变量。

我希望这是有道理的,再次感谢 - 你们统治

4

6 回答 6

2

不,你不能嵌套方法。您可以使用以下几种方法:

  • 您可以在方法中创建匿名函数,并以与调用方法类似的方式调用它们。
  • 您可以在一种方法中将局部变量提升为成员字段,然后您可以从两种方法中访问它们。
于 2010-09-30T11:27:22.087 回答
1

您似乎误解了类代码的工作原理?

GetFileList()不会因为您将它放在类中而执行Execute()- 您必须实际调用它,如下所示:

public class FTPtoFTP : IJob
{
    private static ILog _log = LogManager.GetLogger(typeof(HTTPtoFTP));

    public FTPtoFTP()
    {

    }

    public virtual void Execute(JobExecutionContext context)
    {
        string[] files = GetFileList();

        //Code that executes, the variable context allows me to access the job information
    }

    string[] GetFileList()
    { 
        //Code for getting file list
    }
}

还是我完全误解了你的问题?

于 2010-09-30T11:26:11.807 回答
1

您可以使用 lambda 表达式:

public virtual void Execute(JobExecutionContext context) 
{ 

    Func<string[]> getFileList = () => { /*access context and return an array */};

    string[] strings = getFileList();

} 
于 2010-09-30T11:26:42.203 回答
1

您是否尝试从GetFileList函数中获取结果并将其用于Execute?如果是这样,那么试试这个:

public class FTPtoFTP : IJob
{
    private static ILog _log = LogManager.GetLogger(typeof(HTTPtoFTP));

    public FTPtoFTP()
    {

    }

    public virtual void Execute(JobExecutionContext context)
    {
        //Code that executes, the variable context allows me to access the job information
        string[] file_list = GetFileList();
        // use file_list
    }

    private string[] GetFileList()
    { 
       //Code for getting file list
       return list_of_strings;
    }
}
于 2010-09-30T11:27:56.693 回答
1

Execute是一个虚拟方法,它不是声明其他方法的空间,它是用来放置作业的任何逻辑的空间,它不是声明新方法的命名空间。如果您想使用方法化逻辑,只需在类定义中声明它们并从执行函数中调用它们。

public virtual void Execute(JobExecutionContext context)
{

    mymethod1();
    mymethod2();
}

private void mymethod1()
{}

private void mymethod2()
{}
于 2010-09-30T11:28:15.630 回答
1

似乎您想根据一些上下文信息获取文件列表 - 在这种情况下,只需向GetFileList方法添加一个参数并从以下位置传递它Execute

public virtual void Execute(JobExecutionContext context)
{
    string[] fileList = this.GetFileList(context);
    ...
}

private string[] GetFileList(JobExecutionContext) { ... }
于 2010-09-30T11:31:04.303 回答