LINQ:创建表达式的逻辑反 [英] Linq: Create logical inverse of expression

查看:166
本文介绍了LINQ:创建表达式的逻辑反的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个接受表达式来的方法; Func键< T,BOOL>> 并创建它的逻辑相反(即,它会返回其中,它会返回真正,反之亦然。这是比我想象的要困难得多,这是我在哪里了于:

I would like to create a method that accepts an Expression<Func<T, bool>> and creates the logical inverse of it (i.e. it would return false where it would have returned true, and vice versa. This is much harder than I thought. This is where I am up to:

public static Expression<Func<T, bool>> Not<T>(this Expression<Func<T, bool>> expression)
{
  return Expression.Lambda<Func<T, bool>>(Expression.Not(expression.Body));
}

这编译正常,但抛出时调用以下异常:

This compiles fine but throws the following Exception when called:

Test method Tests.Common.Unit.LinqPredicateBuilderTests.CanInverseAPredicate threw exception: 
System.ArgumentException: Incorrect number of parameters supplied for lambda declaration

我不知道我在做什么。任何人都可以填补空白?

I have no idea what I'm doing. Could anyone fill in the blanks?

推荐答案

您正在呼叫 Expression.Lambda 在所有的时候你应该转发源的单个参数创建一个不带参数的表达式。表达

You're calling Expression.Lambda to create an expression with no parameters at all, when you should be forwarding the single parameter of the source expression.

请注意,我们正试图创建一个表达式来; Func键< T,BOOL>> 而不是一个表达式来; Func键<布尔>>

Note that we are trying to create an Expression<Func<T, bool>> and not an Expression<Func<bool>>.

试试这个:

return Expression.Lambda<Func<T, bool>>(Expression.Not(expression.Body),
                                        expression.Parameters);

这篇关于LINQ:创建表达式的逻辑反的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆