我认为您可以ExpressionVisitor
以简单的方式从该类中派生。这是一个概念证明 - 它可能过于简单化,但我认为这就是你所追求的:
using System;
using System.Linq.Expressions;
class Test
{
static void Main()
{
Expression<Func<int, int, int>> original = (x, y) => MethodX(x) + MethodY(y);
Console.WriteLine("Original: {0}", original);
var partiallyApplied = ApplyPartial(original, 10);
Console.WriteLine("Partially applied: {0}", partiallyApplied);
}
static int MethodX(int x)
{
return x + 1;
}
static int MethodY(int x)
{
return -x;
}
static Expression<Func<T2, TResult>> ApplyPartial<T1, T2, TResult>
(Expression<Func<T1, T2, TResult>> expression, T1 value)
{
var parameter = expression.Parameters[0];
var constant = Expression.Constant(value, parameter.Type);
var visitor = new ReplacementVisitor(parameter, constant);
var newBody = visitor.Visit(expression.Body);
return Expression.Lambda<Func<T2, TResult>>(newBody, expression.Parameters[1]);
}
}
class ReplacementVisitor : ExpressionVisitor
{
private readonly Expression original, replacement;
public ReplacementVisitor(Expression original, Expression replacement)
{
this.original = original;
this.replacement = replacement;
}
public override Expression Visit(Expression node)
{
return node == original ? replacement : base.Visit(node);
}
}
输出:
Original: (x, y) => (MethodX(x) + MethodY(y))
Partially applied: y => (MethodX(10) + MethodY(y))