[英]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.