动态拼接Lambda表达式-表达式目录树动态构建=Expression<Func<int, int, int>> predicate1 = (m, n) => m * n + 2

//IEnuable与IQueryable
//var list = new List<int>().AsQueryable();
//list = list.Where(c => c > 1);//参数:Expression<Func<TSource, bool>> predicate,如:Expression<Func<int, bool>> predicate = c => c > 1;
Expression<Func<int, int, int>> predicate1 = (m, n) => m * n + 2;
//注意:Expression不能使用大括号,来写lambda表达式,如下写法,会报错
//Expression<Func<int, int, int>> predicate2 = delegate (m, n) { return m* n +2};


//var list1 = new List<int>();
//var list2 = list1.Where(c => c > 1);//参数:Func<TSource, bool> predicate,如:Func<int, bool> predicate1 = c => c > 1;
Func<int, bool> predicate6 = c => c > 1;
Func<int, bool> predicate7 = delegate (int c)//delegate可以使用大括号,来写lambda表达式
{
return c > 1;
};

if (predicate7.Invoke(3))
{
Console.WriteLine("调用 Func<int, bool> predicate7 predicate7.Invoke(3) 成功。。。");
}

//构造=====》Expression<Func<int, int, int>> predicate1 = (m, n) => m * n + 2;
//(m, n) => m * n + 2;
//1、左边的参数 (m, n)
var paramM = Expression.Parameter(typeof(int));
var paramN = Expression.Parameter(typeof(int));
//2、m * n + 2;
//2.1 右边的成员字段 m, n
//var fieldM = Expression.Field(typeof(int),"m");
//var fieldN = Expression.Variable(typeof(int), "n");
//2.2 右边的成员字段 m * n
var fieldMN = Expression.Multiply(paramM, paramN);
//2.3 右边的成员常量字段 2
var fieldConstant = Expression.Constant(2, typeof(int));
//2.4 右边的成员m * n + 2;
var memberField = Expression.Add(fieldMN, fieldConstant);
//2.5 右边的成员常量字段 2
Expression<Func<int, int, int>> lam = Expression.Lambda<Func<int, int, int>>(memberField, new ParameterExpression[] { paramM, paramN });
var func = lam.Compile();

var result = func.Invoke(2, 3);
Console.WriteLine($"构造=====》Expression<Func<int, int, int>> predicate1 = (m, n) => m * n + 2 输出结果:{result}");

posted @ 2020-12-02 14:44  龙骑科技  阅读(143)  评论(0编辑  收藏  举报