C# 传递 Lambda 表达式作为方法参数 [英] C# Pass Lambda Expression as Method Parameter

查看:62
本文介绍了C# 传递 Lambda 表达式作为方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 lambda 表达式,我希望能够传递和重用它.代码如下:

I have a lambda expression that I'd like to be able to pass around and reuse. Here's the code:

public List<IJob> getJobs(/* i want to pass the lambda expr in here */) {
  using (SqlConnection connection = new SqlConnection(getConnectionString())) {
    connection.Open();
    return connection.Query<FullTimeJob, Student, FullTimeJob>(sql, 
      (job, student) => {         
        job.Student = student;
        job.StudentId = student.Id;
        return job;
        },
        splitOn: "user_id",
        param: parameters).ToList<IJob>();   
  }   

这里的关键是,我希望能够将我在这里使用的 lambda 表达式传递到调用此代码的方法中,以便我可以重用它.lambda 表达式是我的 .Query 方法中的第二个参数.我假设我想使用 Action 或 Func,但我不太确定它的语法是什么,或者它是如何工作的.有人可以举个例子吗?

The key here, is I want to be able to pass the lambda expression that I'm using here into the method that's calling this code, so I can reuse it. The lambda expression is the second argument inside my .Query method. I'm assuming I'd want to use an Action or Func, but I'm not quite sure what the syntax is for this or how it quite works. Can someone please give me an example?

推荐答案

使用 Func 委托作为参数类型并将其传递给您的Query:

public List<IJob> getJobs(Func<FullTimeJob, Student, FullTimeJob> lambda)
{
  using (SqlConnection connection = new SqlConnection(getConnectionString())) {
    connection.Open();
    return connection.Query<FullTimeJob, Student, FullTimeJob>(sql, 
        lambda,
        splitOn: "user_id",
        param: parameters).ToList<IJob>();   
  }  
}

你会称之为:

getJobs((job, student) => {         
        job.Student = student;
        job.StudentId = student.Id;
        return job;
        });

或者将 lambda 赋值给一个变量并传入 it.

Or assign the lambda to a variable and pass it in.

这篇关于C# 传递 Lambda 表达式作为方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆