【问题标题】:Instantiating a class and calling method in lambda foreach在 lambda foreach 中实例化一个类和调用方法
【发布时间】:2017-11-06 15:16:48
【问题描述】:

是否可以在 ForEach lambda 表达式中执行此操作?

reports.ForEach(x => new PublishReport(x)
      PublishReport.PublishReports());

我要做的是实例化 PublishReport(仅包含类和方法名称)类,传递一个报表对象,然后调用 PublishReport 类的 PublishReports 方法。

我所做的工作是:

reports.ForEach(x => CallPublishReports(x));

private void CallPublishReport(Report report)
{
    PublishReport publishReport = new PublishReport(report);
    publishReport.PublishReports();
}

【问题讨论】:

  • 您是否考虑过改用静态方法?然后你可以打电话给PublishReport.PublishReports(x)
  • 感谢您的建议。没想到。会调查的。

标签: c# lambda foreach


【解决方案1】:

您要查找的代码如下所示:

reports.ForEach(x => (new PublishReport(x)).PublishReport());

或者

reports.ForEach(x => {
    var report = new PublishReport(x);
    report.PublishReports();
});

您也可以将ForEach 替换为Select,因为前者仅存在于PLINQ afaik 中。

【讨论】:

    【解决方案2】:

    您可以先使用Select 创建实例,然后使用ForEach 覆盖它们,如下所示:

    reports
        .Select(r => new PublishReport(r))
        .ForEach(pr => pr.PublishReports());
    

    【讨论】:

      【解决方案3】:

      只需给 lambda 一个主体:

      reports.ForEach(x => 
      {
          PublishReport publishReport = new PublishReport(x);
          publishReport.PublishReports();
      });
      

      【讨论】:

      • 谢谢!上面代码中的PublishReport类实例化的时候,应该是x吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-10
      • 2011-12-30
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 2012-07-05
      相关资源
      最近更新 更多