获取值从ExpressionTrees [英] Getting Values from ExpressionTrees

查看:176
本文介绍了获取值从ExpressionTrees的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让有:

Expression<Func<Customer, bool>> expression = c => c.Name == "John";

现在我通过使用以下方式获得值:

now i get the value by using :

string myvalue = ((ConstantExpression) bin.Right).Value;

现在有:

string x = "John";
Expression<Func<Customer, bool>> expression = c => c.Name == x;

现在我明白了

string myvalue = ((ConstantExpression) bin.Right).Value;

会产生错误,因为bin.right不是常量表达其字段表达式,但问题是如何获取值(John)?

would generate an error because the bin.right here is not constantexpression its a field expression but the question is how do i get the value(John) out of this ?

推荐答案

评估它。这将给你的价值,无论什么样的表达式。

You could wrap the expression in a lambda and then compile and evaluate it. That would give you the value no matter what kind of expression it is.

string myvalue = Expression.Lambda<Func<string>>(bin.Right).Compile().Invoke();

请注意,如果参数c在表达式右侧使用, ,因为它不会被定义。还要注意,在调用Invoke时,这将为您提供右侧的当前值,如果对象中的字段更改,后续调用可能返回不同的值。

Note that this won't work if the parameter c is used on the right hand side of the expression, since it wouldn't be defined. Also note that this will give you the current value of the right hand side when you call Invoke, and subsequent calls could return different values if the field in the object changes.

更新:如果你在编译时不知道右边的类型,但这将打破像int类型值类型。您将需要使用Expression.Convert强制在返回值类型之前将其加框。这将适用于值类型和引用类型:

Update: If you don't know the type of the right hand side at compile time, you can use object, but this will break for value types like int. You will need to use Expression.Convert to force value types to be boxed before returning them. This will work for both value types and reference types:

object myvalue = Expression.Lambda<Func<object>>(
    Expression.Convert(bin.Right, typeof(object))).Compile().Invoke();

您也可以使用非类型化的lambda和DynamicInvoke:

You could also use an untyped lambda and DynamicInvoke:

object myvalue = Expression.Lambda(bin.Right).Compile().DynamicInvoke();

这篇关于获取值从ExpressionTrees的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆