如何从 Expression<Func< , >> 创建委托? (将参数传递给表达式)?

How to create a delegate from Expression<Func< , >>? (pass a parameter to the expression)?

我有以下过滤器:

Expression<Func<Employee, bool>> fromDateFilterFourDays = z => EntityFunctions.TruncateTime(z.FiringDate) >= EntityFunctions.TruncateTime(DateTime.Now.AddDays(-4));

Expression<Func<Employee, bool>> fromDateFilterSixDays = z => EntityFunctions.TruncateTime(z.FiringDate) >= EntityFunctions.TruncateTime(DateTime.Now.AddDays(-6));

如何从这个过滤器中创建委托?

我不想为每个给定的数字(即四天或六天)创建一个变量。

这是通过调用 Invoke() 方法完成的:

fromDateFilterFourDays.Invoke(employee);

或者您可以 Compile() 将表达式添加到函数中,然后调用函数:

var fromDateFilterFourDaysFunc = fromDateFilterFourDays.Compile();

fromDateFilterFourDaysFunc(employee);

您可以使用Compile方法轻松地将Expression<Func<...>>转换为Func<...>

但是,请记住,您提供的示例表达式将不起作用,因为它们使用的 Canonical Functions 只是用于映射相应数据库 SQL 函数的占位符,如果您尝试实际评估它们(这将发生在 Func)。

从另一方面来说,如果问题实际上是如何参数化样本表达式,它可能是这样的

static Expression<Func<Employee, bool>> DateFilter(int currentDateOffset)
{
    return e => EntityFunctions.TruncateTime(e.FiringDate) >= DateTime.Today.AddDays(currentDateOffset);
}

我的理解是你想:

  1. 将两个参数传入委托,员工和天数。
  2. 将该表达式编译成委托。

第一部分可以通过将天数添加到参数列表来完成:

Expression<Func<Employee, int, bool>> fromDateFilter = (z, n) => EntityFunctions.TruncateTime(z.FiringDate) >= EntityFunctions.TruncateTime(DateTime.Now.AddDays(n));

第二个使用编译方法:

var del = fromDateFilter.Compile();
// use it
del(employee, -4);