簡體   English   中英

C#中的類中的方法

[英]Methods in classes in C#

我的項目中的類庫中有許多不同的類。 我正在使用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開始之前執行方法的結束,並且也不允許我訪問所需的上下文變量。

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

不,您不能嵌套方法。 您可以使用以下兩種方法代替:

  • 您可以在方法內部創建匿名函數 ,並以類似於調用方法的方式來調用它們。
  • 您可以在一種方法中將局部變量提升為成員字段,然后可以從這兩種方法中訪問它們。

您似乎誤解了類代碼的工作原理?

GetFileList()不會僅僅因為將它放在Execute()之后的類中而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
    }
}

還是我完全誤解了您的問題?

您可以使用lambda表達式:

public virtual void Execute(JobExecutionContext context) 
{ 

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

    string[] strings = getFileList();

} 

您是否要從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;
    }
}

Execute是一個虛擬方法,它不是用於聲明其他方法的空間,它是在內部放置作業的任何邏輯,而不是用於聲明新方法的名稱空間。 如果要使用方法化的邏輯,只需在類定義中聲明它們,然后從execute函數調用它們即可。

public virtual void Execute(JobExecutionContext context)
{

    mymethod1();
    mymethod2();
}

private void mymethod1()
{}

private void mymethod2()
{}

似乎您想基於一些上下文信息獲取文件列表-在這種情況下,只需將參數添加到GetFileList方法並從Execute傳遞它即可:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM