从 ExpressionTree 获取值
让有:
Expression<Func<Customer, bool>> expression = c => c.Name == "John";
现在我通过使用获得值:
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 不是常量表达式,它是一个字段表达式,但问题是我如何获取值(约翰)出这个?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将表达式包装在 lambda 中,然后编译并计算它。无论它是什么类型的表达,都会给你带来价值。
请注意,如果参数 c 用在表达式的右侧,则这将不起作用,因为它不会被定义。另请注意,当您调用 Invoke 时,这将为您提供右侧的当前值,并且如果对象中的字段发生更改,后续调用可能会返回不同的值。
更新:如果您在编译时不知道右侧的类型,则可以使用 object,但这对于像 int 这样的值类型会中断。您将需要使用 Expression.Convert 在返回值类型之前强制对其进行装箱。这适用于值类型和引用类型:
您还可以使用无类型 lambda 和 DynamicInvoke:
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.
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:
You could also use an untyped lambda and DynamicInvoke: