Getting Values from ExpressionTrees

你。 提交于 2019-12-10 13:38:22

问题


let there be:

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

now i get the value by using :

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

now let there be:

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

now i understand that

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

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 ?


回答1:


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();

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.


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();

You could also use an untyped lambda and DynamicInvoke:

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


来源:https://stackoverflow.com/questions/3457558/getting-values-from-expressiontrees

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!