如何通过MakeGenericType制作通用lambda

时间:2019-03-08 03:09:00

标签: c# linq expression

下面是我的代码片段

        List<int> list = new List<int>() { 1, 2, 3, 4, 5 };

        Func<int, bool> f = c => c > 3;
        var result = list.Where(f);
        Console.WriteLine(result.ToList());

        var param = Expression.Parameter(typeof(int),"c");
        var constant = Expression.Constant(3);
        var body = Expression.GreaterThanOrEqual(param, constant);
        var funcType = typeof(Func<,>).MakeGenericType( typeof(int), typeof(bool));
        var funcDelegate = Expression.Lambda(funcType, body, param);
        result = list.Where(funcDelegate);

        Console.WriteLine(result.ToList());

        Console.ReadLine();

系统告诉我result = list.Where(funcDelegate);是错误的,无法转换"System.Linq.Expressions.LambdaExpression" to "System.Func<int,int,bool>"

我认为使用MakeGenericType方法时一定会出错,如何通过MakeGenericType构建正确的泛型lambda表达式?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用

var funcDelegate = Expression.Lambda<Func<int,bool>>(body, param).Compile();

代替

var funcType = typeof(Func<,>).MakeGenericType( typeof(int), typeof(bool));
var funcDelegate = Expression.Lambda(funcType, body, param);

这样,您就无需强制委托。

(不要忘记Compile()部分)