我有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 我读过这个 how to pass any method as a parameter for another function 但它使用一个Action对象,它不能返回任何东西(据我所知),我想返回一个List
答案 0 :(得分:3)
这应该有效:
List<Source> WithErrorHandling(Func<List<Source>> func)
{
...
var ret = func();
...
return ret;
}
用法:
var taskId = 123;
var res = WithErrorHandling(() => { GetAllSourcesByTaskId(taskId); });
答案 1 :(得分:1)
你可以传递一个Func,它可以带许多输入参数返回一个值:
Func<T1, T2, TResult>
在你的情况下,这样的事情可以起作用:
public List<Source> GetList(Func<List<Source>> getListMethod) {
return getListMethod();
}
然后使用
进行呼叫GetList(() => GetAllSources());
GetList(() => GetAllSourcesByTaskIdPersonId(taskId, personId));
答案 2 :(得分:0)
你能不能将List作为参数传递给你的方法,可能有点整洁?
答案 3 :(得分:0)
嗯,你没有对这些函数中的代码说什么,但如果你在里面使用linq,那么你的方法绝对不是最好的。 你应该使用这样的东西:
IQueriable<SomeType> GetAllSources()
{
return (from source in sources select ...);
}
IQueriable<SomeType> GetAllSourcesByTaskId(int taskId)
{
return (GetAllSources()).Where(source => source.TaskId == taskId);
}