LAMBDA参数不在范围内 - 在构建二元lambda表达式 [英] Lambda Parameter not in scope -- while building binary lambda expression
问题描述
在手工创建一个lambda表达式,我得到一个参数不在范围内的异常。
任何想法,我做错了吗?
公开类OTHERTYPE
{
公共字符串{将First_Name获得;组; }
公共字符串姓氏{搞定;组; }
}
静态无效的主要(字串[] args)
{
表达式来; Func键< OTHERTYPE,布尔>> L2 =
P => p.First_Name ==鲍勃;
l2.Compile(); //作品
的PropertyInfo财产=
typeof运算(OTHERTYPE).GetProperty(将First_Name);
ParameterExpression款=
Expression.Parameter(typeof运算(OTHERTYPE),芭);
常量表达式正确=
Expression.Constant(鲍勃,typeof运算(字符串));
MemberExpression左=
Expression.Property(Expression.Parameter(typeof运算(OTHERTYPE),芭),属性);
BinaryExpression二进制=
Expression.MakeBinary(ExpressionType.Equal,左,右);
表达式来; Func键< OTHERTYPE,布尔>> L =
Expression.Lambda<&Func键LT; OTHERTYPE,布尔>>(二进制,新ParameterExpression [] {}段);
l.Compile(); //获取的lambda参数不在范围内的异常
}
您需要重复使用相同的参数对象。那么,你有:
MemberExpression左= Expression.Property
(Expression.Parameter(typeof运算(OTHERTYPE) 对),属性);
应该是:
MemberExpression左= Expression.Property(对,属性);
我知道这将使感为他们的名字相匹配,但是这只是不是它的工作方式:(
如果它的任何安慰可言,我很少得到纯手工打造的表达式树正确的我第一次在他们发誓一会儿另一方。另一方面,我认为,在足够寒冷的日子里,马克·Gravell可以仔细呼气,他的呼吸将在完美的,冷冰冰的表达式树代码...
的形式问世
When creating a lambda expression by hand I get a 'Parameter not in scope' exception.
Any ideas as to what I am doing wrong?
public class OtherType
{
public string First_Name { get; set; }
public string Last_Name { get; set; }
}
static void Main(string[] args)
{
Expression<Func<OtherType, bool>> l2 =
p => p.First_Name == "Bob";
l2.Compile(); // Works
PropertyInfo property =
typeof(OtherType).GetProperty("First_Name");
ParameterExpression para =
Expression.Parameter(typeof(OtherType), "para");
ConstantExpression right =
Expression.Constant("Bob", typeof(string));
MemberExpression left =
Expression.Property(Expression.Parameter(typeof(OtherType), "para"), property);
BinaryExpression binary =
Expression.MakeBinary(ExpressionType.Equal, left, right);
Expression<Func<OtherType, bool>> l =
Expression.Lambda<Func<OtherType, bool>>(binary, new ParameterExpression[] { para });
l.Compile(); // Get a 'Lambda Parameter not in scope' exception
}
You need to reuse the same parameter object. So where you've got:
MemberExpression left = Expression.Property
(Expression.Parameter(typeof(OtherType), "para"), property);
it should be:
MemberExpression left = Expression.Property(para, property);
I know it would make sense for them to match by name, but that's just not the way it works :(
If it's any consolation at all, I very rarely get hand-built expression trees right first time. I have to swear at them for a while. On the other hand, I believe that on cold enough days, Marc Gravell can exhale carefully and his breath will come out in the form of perfect, frosty expression tree code...
这篇关于LAMBDA参数不在范围内 - 在构建二元lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!