构建LINQ EX pression树:如何让变量的作用域 [英] Building a LINQ expression tree: how to get variable in scope
问题描述
我要建一个LINQ EX pression树,但它不会编译,因为涉嫌局部变量 $ VAR1
超出范围:
I'm building a LINQ expression tree but it won't compile because allegedly the local variable $var1
is out of scope:
变量'''从范围引用的,但它没有定义System.Object的'类型'的
这是前pression树:
This is the expression tree:
.Block() {
$var1;
.If ($n.Property1 == null) {
.Block() {
$var1 = null;
.Return #Label1 { }
}
} .Else {
.Default(System.Void)
};
$var1 = (System.Object)($n.Property1).Length;
.Label
.LabelTarget #Label1:;
$var1
}
下面code是负责建设的树。这是一个更大的东西的一部分,所以我不希望它的目的是从这个例子非常清楚。
The following code is responsible for building the tree. It is part of something larger, therefore I don't expect its purpose to be perfectly clear from this example.
MemberExpression sourceExpression = ...;
List<Expression> expressions = new List<Expression>();
LabelTarget returnTarget = Expression.Label();
ParameterExpression resultVariable = Expression.Variable(typeof(object));
expressions.Add(resultVariable);
expressions.Add(
Expression.IfThen(
Expression.Equal(sourceExpression, Expression.Constant(null)),
Expression.Block(
Expression.Assign(resultVariable, Expression.Constant(null)),
Expression.Return(returnTarget))));
expressions.Add(
Expression.Assign(
resultVariable,
Expression.Convert(sourceExpression, typeof(object))));
expressions.Add(Expression.Label(returnTarget));
expressions.Add(resultVariable);
Expression finalExpression = Expression.Block(expressions);
object result = Expression.Lambda<Func<object>>(finalExpression).Compile()();
所以,问题是:我如何才能在局部变量为范围,以使前pression编译成功地
So the question is: how do I get the local variable into scope so that the expression compiles succesfully?
推荐答案
傻冒添加防爆pression.Variable
正常的名单前pressions块中的 - 你应该使用过载,它指定的变量也分别申报块< /一>:
Your'e adding the Expression.Variable
to the list of "normal" expressions in the block - you should use the overload which specifies the variables do declare for the block separately:
Expression finalExpression = Expression.Block(new[] { resultVariable },
expressions);
(并删除调用 EX pressions.Add(resultVariable);
)
这篇关于构建LINQ EX pression树:如何让变量的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!