简体   繁体   中英

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> )

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).

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.

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

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<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. 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM