Skip to main content
 首页 » 编程设计

C#如何将 'any'函数作为参数传递给另一个函数

2024年02月23日15java哥

我有 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> 

我希望能够将它们作为参数传递给函数。

我应该如何声明被调用的函数?

附言 我读过这个 how to pass any method as a parameter for another function 但它使用一个不能返回任何东西的 Action 对象(据我所知),我想返回一个列表

请您参考如下方法:

这应该有效:

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

用法:

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