如何获得Lambda表达式的值 [英] How to get the value of a lambda expression
本文介绍了如何获得Lambda表达式的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我们有以下内容:
Say we have the following :
private static string Query<T>(Expression<Func<T, bool>> pr)
{
return pr.ToString();
}
...
int ii = 1000;
string str = Query((SalesInvoiceRow r) => r.Serial > ii && r.CustomerName.Contains( "23"));
当您运行上面的代码时,我们得到:
When you run the above we get:
r => ((r.Serial > value(testing.program+<>c__DisplayClass0).ii) AndAlso r.CustomerName.Contains("23"))
如何获得ii
的值,而不是如下所示的丑陋语句?
How can we get the value of ii
instead of the ugly statement like below?
r => ((r.Serial > 1000) AndAlso r.CustomerName.Contains("23"))
推荐答案
Hello Mehdi,
这是一些与ExpressionVisitor一起调整的实验代码:
Hello Mehdi,
This is some experimental code to tweak with the ExpressionVisitor:
static void Main(string[] args)
{
int a = 5;
int b = 100;
Expression<Func<int, bool>> expr = v => v > (a + b);
WalkVisitor w = new WalkVisitor();
w.Visit(expr);
}
public class WalkVisitor : ExpressionVisitor
{
protected override Expression VisitMember(MemberExpression node)
{
var e = base.VisitMember(node);
var c = node.Expression as ConstantExpression;
if (c != null)
{
Type t = c.Value.GetType();
var x = t.InvokeMember(node.Member.Name, BindingFlags.GetField,
null, c.Value, null);
Console.WriteLine("{0} = {1}", node.ToString(), x);
}
return e;
}
}
输出为:
The output is:
value(ExprVisitor.Program+<>c__DisplayClass0).a = 5
value(ExprVisitor.Program+<>c__DisplayClass0).b = 100
您可能需要围绕此代码段实现打印访问者...
干杯
Andi
You might need to implement a print visitor around this snippet...
Cheers
Andi
您应该能够编译该表达式,然后对其进行ToString.
You should be able to compile the expression and then ToString it.
pr.Compile().ToString();
我只是意识到您想要ii
.我现在很困惑.您不是将ii设置为1000
吗?您为什么现在想要该值?
也许您是想让查询解决.好吧,你应该做我随后发表的事情,Compile
:)
I just realized you want ii
. I am totally confused now. Aren''t you setting ii to 1000
? Why do you now want the value?
Maybe you meant you want the query resolved. Well you should do what I posted then, Compile
:)
这篇关于如何获得Lambda表达式的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文