Heim > Fragen und Antworten > Hauptteil
因为项目中用到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) }
));
}