Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linq 这个PredicateBuilder类是如何工作的?_Linq_C# 4.0 - Fatal编程技术网

Linq 这个PredicateBuilder类是如何工作的?

Linq 这个PredicateBuilder类是如何工作的?,linq,c#-4.0,Linq,C# 4.0,我一直在读约瑟夫·阿尔巴哈里(Joseph Albahari)关于C#4.0的精彩著作,我遇到了这样一门课: public static class PredicateBuilder { public static Expression<Func<T, bool>> True<T> () { return f => true; } public static Expression<Func<T, boo

我一直在读约瑟夫·阿尔巴哈里(Joseph Albahari)关于C#4.0的精彩著作,我遇到了这样一门课:

public static class PredicateBuilder
    {
        public static Expression<Func<T, bool>> True<T> () { return f => true; }
        public static Expression<Func<T, bool>> False<T> () { return f => false; }

        public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
                                                  Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());

            return Expression.Lambda<Func<T, bool>>
                 (Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
        }

        public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
                                                   Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
            return Expression.Lambda<Func<T, bool>>
                 (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
        }
    }
我知道Func是一个委托,它应该返回true或false,但是这段代码通常做什么呢

提前感谢:)

这用于从两个表示谓词的输入表达式“构建”谓词

表达式树是一种使用lambda生成树状结构(而不是直接委托)中代码表示的方法。这将获取两个表示谓词的表达式树(
expression
),并将它们组合到一个新的表达式树中,表示“or”大小写(以及第二个方法中的“and”大小写)


表达式树及其相应的实用程序(如上面所述)对于ORM之类的东西很有用。例如,实体框架使用带有
IQueryable
的表达式树,将定义为lambda的“代码”转换为在服务器上运行的SQL。

@Kar:他正在使用这两个表达式,并构建一个在第一种情况下有效的“expression1 | | expression2”和“expression1&&expression2”在第二种情况下…-感谢他创建了许多超出我想象的奇怪类,如ExpressionVisitor等。我会在遇到这些疑问时发布这些疑问。-你能告诉我为什么他在Invoke中使用expr2作为第一个参数而不是expr1,然后将expr2.parameters.cast作为第二个参数传递吗?
var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());

                return Expression.Lambda<Func<T, bool>>
                     (Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);