强制 .NET 表达式使用当前值
Force a .NET Expression to Use Current Value
我想知道是否有办法强制 C# 表达式将表达式的一部分转换为值。我正在调用一个接受定义查询的表达式的方法。我在标识查询的对象中有一系列值。这是一个简化的例子:
var identifier = new { id = 5 };
context.SomeMethod(i=>i.Id == identifier.Id);
这失败了。根据我看到的错误,表达式似乎试图将 "identifier.Id" 合并到表达式中,而不是将 "identifier.Id" 解析为它的值,即 5。以下代码有效:
var id = 5;
context.SomeMethod(i=>i.Id == id)
虽然这有效,但这是一个简化的示例,在我的实际代码中这会很痛苦。所以我的问题是,是否有一些语法可以用来包装表达式的一部分以强制它解析为一个值?
C# 不支持任何类型的匿名委托/表达式的显式捕获规则。
您的解决方法就是解决方法。
在 this blog entry 中讨论了如何简化 Expression
。它采用两遍方法,首先将所有不是参数且没有参数的节点标记为子节点,然后再执行另一遍,对这些节点进行评估,以便可以在没有参数的情况下计算任何内容依靠参数被评估。
这是经过一些小调整的代码:
public static class Evaluator
{
/// <summary>
/// Performs evaluation & replacement of independent sub-trees
/// </summary>
/// <param name="expression">The root of the expression tree.</param>
/// <param name="fnCanBeEvaluated">A function that decides whether a given expression node can be part of the local function.</param>
/// <returns>A new tree with sub-trees evaluated and replaced.</returns>
public static Expression PartialEval(Expression expression, Func<Expression, bool> fnCanBeEvaluated)
{
return new SubtreeEvaluator(new Nominator(fnCanBeEvaluated).Nominate(expression)).Eval(expression);
}
/// <summary>
/// Performs evaluation & replacement of independent sub-trees
/// </summary>
/// <param name="expression">The root of the expression tree.</param>
/// <returns>A new tree with sub-trees evaluated and replaced.</returns>
public static Expression PartialEval(Expression expression)
{
return PartialEval(expression, Evaluator.CanBeEvaluatedLocally);
}
private static bool CanBeEvaluatedLocally(Expression expression)
{
return expression.NodeType != ExpressionType.Parameter;
}
/// <summary>
/// Evaluates & replaces sub-trees when first candidate is reached (top-down)
/// </summary>
class SubtreeEvaluator : ExpressionVisitor
{
HashSet<Expression> candidates;
internal SubtreeEvaluator(HashSet<Expression> candidates)
{
this.candidates = candidates;
}
internal Expression Eval(Expression exp)
{
return this.Visit(exp);
}
public override Expression Visit(Expression exp)
{
if (exp == null)
{
return null;
}
if (this.candidates.Contains(exp))
{
return this.Evaluate(exp);
}
return base.Visit(exp);
}
private Expression Evaluate(Expression e)
{
if (e.NodeType == ExpressionType.Constant)
{
return e;
}
LambdaExpression lambda = Expression.Lambda(e);
Delegate fn = lambda.Compile();
return Expression.Constant(fn.DynamicInvoke(null), e.Type);
}
}
/// <summary>
/// Performs bottom-up analysis to determine which nodes can possibly
/// be part of an evaluated sub-tree.
/// </summary>
class Nominator : ExpressionVisitor
{
Func<Expression, bool> fnCanBeEvaluated;
HashSet<Expression> candidates;
bool cannotBeEvaluated;
internal Nominator(Func<Expression, bool> fnCanBeEvaluated)
{
this.fnCanBeEvaluated = fnCanBeEvaluated;
}
internal HashSet<Expression> Nominate(Expression expression)
{
this.candidates = new HashSet<Expression>();
this.Visit(expression);
return this.candidates;
}
public override Expression Visit(Expression expression)
{
if (expression != null)
{
bool saveCannotBeEvaluated = this.cannotBeEvaluated;
this.cannotBeEvaluated = false;
base.Visit(expression);
if (!this.cannotBeEvaluated)
{
if (this.fnCanBeEvaluated(expression))
{
this.candidates.Add(expression);
}
else
{
this.cannotBeEvaluated = true;
}
}
this.cannotBeEvaluated |= saveCannotBeEvaluated;
}
return expression;
}
}
}
还有一个附加方法,可以在 IQueryable<T>
而不是 Expression
上调用它
class Query<T> : IQueryable<T>
{
private IQueryProvider provider;
private Expression expression;
public Query(IQueryProvider provider, Expression expression)
{
this.provider = provider;
this.expression = expression;
}
public IEnumerator<T> GetEnumerator()
{
return ((IEnumerable<T>)this.Provider.Execute(this.Expression)).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)this.Provider.Execute(this.Expression)).GetEnumerator();
}
public Type ElementType
{
get { return typeof(T); }
}
public Expression Expression
{
get { return expression; }
}
public IQueryProvider Provider
{
get { return provider; }
}
}
public static IQueryable<T> Simplify<T>(this IQueryable<T> query)
{
return new Query<T>(query.Provider, Evaluator.PartialEval(query.Expression));
}
您现在可以写:
var identifier = new { id = 5 };
var query context.SomeMethod(i=>i.Id == identifier.Id)
.Simplify();
最后得到一个有效的查询:
context.SomeMethod(i=>i.Id == 5)
我想知道是否有办法强制 C# 表达式将表达式的一部分转换为值。我正在调用一个接受定义查询的表达式的方法。我在标识查询的对象中有一系列值。这是一个简化的例子:
var identifier = new { id = 5 };
context.SomeMethod(i=>i.Id == identifier.Id);
这失败了。根据我看到的错误,表达式似乎试图将 "identifier.Id" 合并到表达式中,而不是将 "identifier.Id" 解析为它的值,即 5。以下代码有效:
var id = 5;
context.SomeMethod(i=>i.Id == id)
虽然这有效,但这是一个简化的示例,在我的实际代码中这会很痛苦。所以我的问题是,是否有一些语法可以用来包装表达式的一部分以强制它解析为一个值?
C# 不支持任何类型的匿名委托/表达式的显式捕获规则。
您的解决方法就是解决方法。
在 this blog entry 中讨论了如何简化 Expression
。它采用两遍方法,首先将所有不是参数且没有参数的节点标记为子节点,然后再执行另一遍,对这些节点进行评估,以便可以在没有参数的情况下计算任何内容依靠参数被评估。
这是经过一些小调整的代码:
public static class Evaluator
{
/// <summary>
/// Performs evaluation & replacement of independent sub-trees
/// </summary>
/// <param name="expression">The root of the expression tree.</param>
/// <param name="fnCanBeEvaluated">A function that decides whether a given expression node can be part of the local function.</param>
/// <returns>A new tree with sub-trees evaluated and replaced.</returns>
public static Expression PartialEval(Expression expression, Func<Expression, bool> fnCanBeEvaluated)
{
return new SubtreeEvaluator(new Nominator(fnCanBeEvaluated).Nominate(expression)).Eval(expression);
}
/// <summary>
/// Performs evaluation & replacement of independent sub-trees
/// </summary>
/// <param name="expression">The root of the expression tree.</param>
/// <returns>A new tree with sub-trees evaluated and replaced.</returns>
public static Expression PartialEval(Expression expression)
{
return PartialEval(expression, Evaluator.CanBeEvaluatedLocally);
}
private static bool CanBeEvaluatedLocally(Expression expression)
{
return expression.NodeType != ExpressionType.Parameter;
}
/// <summary>
/// Evaluates & replaces sub-trees when first candidate is reached (top-down)
/// </summary>
class SubtreeEvaluator : ExpressionVisitor
{
HashSet<Expression> candidates;
internal SubtreeEvaluator(HashSet<Expression> candidates)
{
this.candidates = candidates;
}
internal Expression Eval(Expression exp)
{
return this.Visit(exp);
}
public override Expression Visit(Expression exp)
{
if (exp == null)
{
return null;
}
if (this.candidates.Contains(exp))
{
return this.Evaluate(exp);
}
return base.Visit(exp);
}
private Expression Evaluate(Expression e)
{
if (e.NodeType == ExpressionType.Constant)
{
return e;
}
LambdaExpression lambda = Expression.Lambda(e);
Delegate fn = lambda.Compile();
return Expression.Constant(fn.DynamicInvoke(null), e.Type);
}
}
/// <summary>
/// Performs bottom-up analysis to determine which nodes can possibly
/// be part of an evaluated sub-tree.
/// </summary>
class Nominator : ExpressionVisitor
{
Func<Expression, bool> fnCanBeEvaluated;
HashSet<Expression> candidates;
bool cannotBeEvaluated;
internal Nominator(Func<Expression, bool> fnCanBeEvaluated)
{
this.fnCanBeEvaluated = fnCanBeEvaluated;
}
internal HashSet<Expression> Nominate(Expression expression)
{
this.candidates = new HashSet<Expression>();
this.Visit(expression);
return this.candidates;
}
public override Expression Visit(Expression expression)
{
if (expression != null)
{
bool saveCannotBeEvaluated = this.cannotBeEvaluated;
this.cannotBeEvaluated = false;
base.Visit(expression);
if (!this.cannotBeEvaluated)
{
if (this.fnCanBeEvaluated(expression))
{
this.candidates.Add(expression);
}
else
{
this.cannotBeEvaluated = true;
}
}
this.cannotBeEvaluated |= saveCannotBeEvaluated;
}
return expression;
}
}
}
还有一个附加方法,可以在 IQueryable<T>
而不是 Expression
class Query<T> : IQueryable<T>
{
private IQueryProvider provider;
private Expression expression;
public Query(IQueryProvider provider, Expression expression)
{
this.provider = provider;
this.expression = expression;
}
public IEnumerator<T> GetEnumerator()
{
return ((IEnumerable<T>)this.Provider.Execute(this.Expression)).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)this.Provider.Execute(this.Expression)).GetEnumerator();
}
public Type ElementType
{
get { return typeof(T); }
}
public Expression Expression
{
get { return expression; }
}
public IQueryProvider Provider
{
get { return provider; }
}
}
public static IQueryable<T> Simplify<T>(this IQueryable<T> query)
{
return new Query<T>(query.Provider, Evaluator.PartialEval(query.Expression));
}
您现在可以写:
var identifier = new { id = 5 };
var query context.SomeMethod(i=>i.Id == identifier.Id)
.Simplify();
最后得到一个有效的查询:
context.SomeMethod(i=>i.Id == 5)