繁体   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