【问题标题】:C# how to pass 'any' function as a parameter to another functionC#如何将'any'函数作为参数传递给另一个函数
【发布时间】:2012-02-21 10:06:53
【问题描述】:

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

【问题讨论】:

  • 使用Func 代替Action
  • 给定的函数都有不同的参数,你打算如何提供正确的参数?
  • @Roger 我试过了,但我无法让它工作。在我看来,一个函数只有一个签名(如果我错了,请纠正我)所以当我为 GetAllSources() 声明一个函数时,我无法通过 GetAllSourcesByTaskId(int taskId)
  • @GregL:我不知道,但我想我可以这样做:List&lt;Source&gt; = GetDataFromGenericErrorHhandlingFunction(Dataservice.GetAllSourcesByTaskId(6));
  • @Michel 您的示例只是调用Dataservice.GetAllSourcesByTaskId() 函数并将返回值传递给GetDataFromGenericErrorHhandlingFunction() 方法。那是容易的事。我错过了什么吗?

标签: c#


【解决方案1】:

这应该可行:

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

用法:

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

【讨论】:

  • 太棒了!我没有做并使它失败的是:() =&gt; { GetAllSourcesByTaskId(taskId); };相反,我这样做了:GetAllSourcesByTaskId(taskId);。当你有一个没有参数的函数时,这确实有效(所以这可以GetAllSources 作为参数),但我现在知道,当你传入一个带参数的函数时,这不是。
【解决方案2】:

您可以传递一个Func,它可以接受许多输入参数并返回一个值:

Func<T1, T2, TResult> 

在你的情况下,这样的事情可能会起作用:

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

然后调用使用

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

【讨论】:

    【解决方案3】:

    你能不能只将 List 作为参数传递给你的方法,可能会更整洁一些?

    【讨论】:

      【解决方案4】:

      好吧,你没有说这些函数里面的代码,但是如果你在里面使用 linq,那么你的方法肯定不是最好的。 你应该使用这样的东西:

      IQueriable<SomeType> GetAllSources()
      {
          return (from source in sources select ...);
      }
      
      IQueriable<SomeType> GetAllSourcesByTaskId(int taskId)
      {
          return (GetAllSources()).Where(source => source.TaskId == taskId);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-19
        • 1970-01-01
        • 2023-01-12
        • 1970-01-01
        • 2013-04-13
        • 2017-08-07
        相关资源
        最近更新 更多