簡體   English   中英

C#如何將“ any”函數作為參數傳遞給另一個函數

[英]C# how to pass 'any' function as a parameter to another function

我有5個數據函數,它們都返回相同類型的對象( List<source>

現在,我必須將它們發布在WCF中,其中必須用各種錯誤處理代碼(大約50行)將調用的代碼括起來。

所以我想:因為代碼(51行)除了要獲取數據的那一行外都是相同的,所以只需創建一個帶有所有錯誤處理的函數,然后將函數作為參數傳遞給該函數。

所以我有這些功能:

GetAllSources() : List<Source>
GetAllSourcesByTaskId(int taskId) : List<Source>
GetAllSourcesByTaskIdPersonId(int taskId, int personId) : List<Source>
GetAllSourcesByDate(DateTime startDate, DateTime endDate): List<Source>

我希望能夠將它們作為參數傳遞給函數。

我應該如何聲明被調用的函數?

PS我已經讀過這個如何傳遞任何方法作為另一個函數的參數,但它使用的操作對象不能返回任何東西(據我所知),我想返回一個列表

這應該工作:

List<Source> WithErrorHandling(Func<List<Source>> func)
{
    ...
    var ret = func();
    ...
    return ret;
 }

用法:

 var taskId = 123;
 var res = WithErrorHandling(() => { GetAllSourcesByTaskId(taskId); });

您可以傳遞一個Func ,它可以接受許多輸入參數並返回一個值:

Func<T1, T2, TResult> 

在您的情況下,可能會發生以下情況:

public List<Source> GetList(Func<List<Source>> getListMethod) {
    return getListMethod();
}

然后使用

GetList(() => GetAllSources());
GetList(() => GetAllSourcesByTaskIdPersonId(taskId, personId));

您能否僅將List作為參數傳遞到您的方法中,可能會更整潔?

嗯,您沒有對這些函數中的代碼進行任何說明,但是,如果在內部使用linq,則您的方法肯定不是最佳方法。 您應該使用這樣的東西:

IQueriable<SomeType> GetAllSources()
{
    return (from source in sources select ...);
}

IQueriable<SomeType> GetAllSourcesByTaskId(int taskId)
{
    return (GetAllSources()).Where(source => source.TaskId == taskId);
}

暫無
暫無

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

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