mongodb - 在MongoQueryProvider 的 Execute方法中, 为什么要判断表达式树类型为LambdaExpression
伊谢尔伦
伊谢尔伦 2017-04-26 09:01:50
0
0
725

因为项目中用到linq to mongo,所以我看了一下MongoQueryProvider 的实现.
但是我不明白这段代码的意思

public object Execute(Expression expression)
{
    var plan = BuildExecutionPlan(expression);

    var lambda = expression as LambdaExpression;
    if (lambda != null)
    {
        var fn = Expression.Lambda(lambda.Type, plan, lambda.Parameters);
        return fn.Compile();
    }
    else
    {
        var efn = Expression.Lambda<Func<object>>(Expression.Convert(plan, typeof(object)));
        var fn = efn.Compile();
        return fn();
    }
}

在什么情况下expression会是LambdaExpression类型呢?
因为IQueryable的扩展方法,调用的是Expression.Call()来生成的表达式树,
用linq表达式生成的表达式树都会是 MethodCallExpression类型
就像下面这样

public static IQueryable<TResult> Select<TSource,TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector) {
            if (source == null)
                throw Error.ArgumentNull("source");
            if (selector == null)
                throw Error.ArgumentNull("selector");
            return source.Provider.CreateQuery<TResult>( 
                Expression.Call(
                    null,
                    ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TResult)), 
                    new Expression[] { source.Expression, Expression.Quote(selector) }
                    ));
        }
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(0)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!