我正在尝试组合这样的函数列表.
我有这个:
Func[] criteria = new Func [3]; criteria[0] = i => i % 2 == 0; criteria[1] = i => i % 3 == 0; criteria[2] = i => i % 5 == 0;
我想要这个:
Func[] predicates = new Func [3]; predicates[0] = i => i % 2 == 0; predicates[1] = i => i % 2 == 0 && i % 3 == 0; predicates[2] = i => i % 2 == 0 && i % 3 == 0 && i % 5 == 0;
到目前为止,我有以下代码:
Expression>[] results = new Expression >[criteria.Length]; for (int i = 0; i < criteria.Length; i++) { results[i] = f => true; for (int j = 0; j <= i; j++) { Expression > expr = b => criteria[j](b); var invokedExpr = Expression.Invoke( expr, results[i].Parameters.Cast ()); results[i] = Expression.Lambda >( Expression.And(results[i].Body, invokedExpr), results[i].Parameters); } } var predicates = results.Select(e => e.Compile()).ToArray(); Console.WriteLine(predicates[0](6)); // Returns true Console.WriteLine(predicates[1](6)); // Returns false Console.WriteLine(predicates[2](6)); // Throws an IndexOutOfRangeException
有谁知道我做错了什么?
无需拉动表达式......
Func[] criteria = new Func [3]; criteria[0] = i => i % 2 == 0; criteria[1] = i => i % 3 == 0; criteria[2] = i => i % 5 == 0; Func [] predicates = new Func [3]; predicates[0] = criteria[0]; for (int i = 1; i < criteria.Length; i++) { //need j to be an unchanging int, one for each loop execution. int j = i; predicates[j] = x => predicates[j - 1](x) && criteria[j](x); } Console.WriteLine(predicates[0](6)); //True Console.WriteLine(predicates[1](6)); //True Console.WriteLine(predicates[2](6)); //False