[英]Instantiating a class and calling method in lambda foreach
Is it possible to do this in a ForEach lambda expression? 是否可以在ForEach lambda表达式中执行此操作?
reports.ForEach(x => new PublishReport(x)
PublishReport.PublishReports());
What I'm trying to do is instantiate the PublishReport (bare with the class and method name) class passing a report object and then calling the PublishReports method of the PublishReport class. 我想做的是实例化PublishReport(带有类和方法名的类)类,该类传递一个报告对象,然后调用PublishReport类的PublishReports方法。
The work around I have done is: 我所做的工作是:
reports.ForEach(x => CallPublishReports(x));
private void CallPublishReport(Report report)
{
PublishReport publishReport = new PublishReport(report);
publishReport.PublishReports();
}
The code you're looking for looks something like this: 您要查找的代码如下所示:
reports.ForEach(x => (new PublishReport(x)).PublishReport());
Or 要么
reports.ForEach(x => {
var report = new PublishReport(x);
report.PublishReports();
});
You can replace ForEach
, with Select
, as well, as the former only exists in PLINQ afaik. 您也可以用Select
替换ForEach
,因为前者仅存在于PLINQ afaik中。
You can do it by first using Select
to create the instances then ForEach
over them like this: 您可以先使用Select
创建实例,然后对它们进行ForEach
,如下所示:
reports
.Select(r => new PublishReport(r))
.ForEach(pr => pr.PublishReports());
Just give the lambda a body: 只需给lambda一个身体即可:
reports.ForEach(x =>
{
PublishReport publishReport = new PublishReport(x);
publishReport.PublishReports();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.