2010-09-30 16 views
0

我的項目中有許多不同的類位於類庫中。我正在使用Quartz.NET(一個調度系統)來調度和加載作業,而實際的作業執行是在這些類庫中完成的。我計劃有很多類型的工作類型,每個類都有自己的類,以便在類庫中執行。C中的類中的方法#

我遇到的問題是我無法在這些類中嵌套方法。例如,這裏是我的課:

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開始之前,也不讓我訪問我需要的上下文變量。

我希望這是有道理的,再次感謝 - 你們治

+0

你在哪裏試圖把字符串[] GetFileList函數 – Thakur 2010-09-30 11:30:16

回答

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

或已我完全誤解了你的問題嗎?

1

你可以使用lambda表達式:

public virtual void Execute(JobExecutionContext context) 
{ 

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

    string[] strings = getFileList(); 

} 
2

不,你不能嵌套的方法。這裏有幾種方法可以用來代替:

  • 您可以在內部創建anonymous functions方法,並以類似調用方法的方式調用它們。
  • 您可以將一種方法中的局部變量提升爲成員字段,然後您可以從兩種方法中訪問它們。
+0

...或者你可以傳遞上下文變量到一個私人'GetFileList'作爲參數! – Timwi 2010-09-30 11:50:02

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

Execute是一個虛擬的方法,它不是一個空間來聲明額外的方法,內你打算把作業任何邏輯,它不是一個命名空間聲明新的方法。如果你想使用方法化邏輯,只需在類定義中聲明它們並從execute函數中調用它們。

public virtual void Execute(JobExecutionContext context) 
{ 

    mymethod1(); 
    mymethod2(); 
} 

private void mymethod1() 
{} 

private void mymethod2() 
{} 
1

看來你要基於一些背景信息來獲取文件列表 - 在這種情況下只是一個參數從Execute添加到GetFileList方法,並把它傳遞:

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

private string[] GetFileList(JobExecutionContext) { ... }