简体   繁体   English

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

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

i have 5 datafunctions which all return the same type of object ( List<source> ) 我有5个数据函数,它们都返回相同类型的对象( List<source>

Now i have to publish them in a WCF in which i have to surround the called code with all kind of error handling code (about 50 lines). 现在,我必须将它们发布在WCF中,其中必须用各种错误处理代码(大约50行)将调用的代码括起来。

So i thought: because the code (51 lines) is all the same except the one line to get the data, just create one function with all the errorhandling a pass the function to get the data as a parameter to that function. 所以我想:因为代码(51行)除了要获取数据的那一行外都是相同的,所以只需创建一个带有所有错误处理的函数,然后将函数作为参数传递给该函数。

So i have these functions: 所以我有这些功能:

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

and i want be able to pass them as a parameter to a function. 我希望能够将它们作为参数传递给函数。

How should i declare the called function? 我应该如何声明被调用的函数?

ps i've read this one how to pass any method as a parameter for another function but it uses an Action object which can't return anything (as far as i understand) and i want to return a List PS我已经读过这个如何传递任何方法作为另一个函数的参数,但它使用的操作对象不能返回任何东西(据我所知),我想返回一个列表

This should work: 这应该工作:

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

Usage: 用法:

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

You can pass a Func which can take many input parameters are return a value: 您可以传递一个Func ,它可以接受许多输入参数并返回一个值:

Func<T1, T2, TResult> 

In your case something like this could work: 在您的情况下,可能会发生以下情况:

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

Then call using 然后使用

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

您能否仅将List作为参数传递到您的方法中,可能会更整洁?

Well, you didn't say anything about the code inside these functions, but if you use linq inside, than your approach is definitely not the best one. 嗯,您没有对这些函数中的代码进行任何说明,但是,如果在内部使用linq,则您的方法肯定不是最佳方法。 You should use something like this: 您应该使用这样的东西:

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