作为主题,怎么两个表达式组合成一个单一的一个这种情况:
Expression<Func<IEnumerable<T>, IEnumerable<T>>> exp1;
Expression<Func<IEnumerable<T>, IEnumerable<T>>> exp2;
Expression<Func<IEnumerable<T>, IEnumerable<T>>> result = ???; // exp1(exp2)
作为主题,怎么两个表达式组合成一个单一的一个这种情况:
Expression<Func<IEnumerable<T>, IEnumerable<T>>> exp1;
Expression<Func<IEnumerable<T>, IEnumerable<T>>> exp2;
Expression<Func<IEnumerable<T>, IEnumerable<T>>> result = ???; // exp1(exp2)
这的确是结合两个的只是一个特定的形式Expression<Func<T, T>>
值。 下面是这样做的一个例子:
using System;
using System.Linq.Expressions;
public class Test
{
public static Expression<Func<T, T>> Apply<T>
(Expression<Func<T, T>> first, Expression<Func<T, T>> second)
{
ParameterExpression input = Expression.Parameter(typeof(T), "input");
Expression invokedSecond = Expression.Invoke(second,
new Expression[]{input});
Expression invokedFirst = Expression.Invoke(first,
new[]{invokedSecond});
return Expression.Lambda<Func<T, T>>(invokedFirst, new[]{input});
}
static void Main()
{
var addAndSquare = Apply<int>(x => x + 1,
x => x * x);
Console.WriteLine(addAndSquare.Compile()(5));
}
}
你可以写ApplySequence
在这些方面很容易,如果你想:
public static Expression<Func<IEnumerable<T>, IEnumerable<T>>>
ApplySequence<T>
(Expression<Func<IEnumerable<T>, IEnumerable<T>>> first,
Expression<Func<IEnumerable<T>, IEnumerable<T>>> second)
{
return Apply(first, second);
}