获取EX pression树里面的方法参数的值 [英] Getting the values of method parameters inside expression trees

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

问题描述

我瞎搞与前pression树,不过我有点卡住了。

I'm messing around with expression trees, but I'm little stuck.

我有这样的EX pression:

I have this expression:

Expression<Func<IX, int>> expr = i => i.GetAll(1, b, method());

其中:

int b = 2;

public static int method()
{
    return 3;
}

public interface IX
{
    int GetAll(int a, int b, int c);
}

现在我想的方法和参数的值,该方法的名称。该方法的名称是很容易的,但参数值是困难的部分。我知道我可以分析他们自己,但我需要处理所有的情况下( ConstantEx pression MemberEx pression MethodCallEx pression ,也许更多的,我不知道)。所以我在想,如果有一般的方式来获得它们的值。如1,2,3

Now I want to get name of the method and values of parameters for this method. Name of the method is easy, but parameter values are harder part. I know I can parse them myself, but I would need to handle all cases (ConstantExpression, MemberExpression, MethodCallExpression and maybe more I'm not aware of). So I was thinking if there was "general" way to get their values. eg 1, 2, 3.

推荐答案

您可以得到 MethodCallEx pression 的有问题的争论  并创建编译 Func键&LT;对象&gt; - 从他们(拳击的价值类型,如果必要的话),然后可以计算

You can get the arguments of the MethodCallExpression in question and create compiled Func<object>s from them (boxing value-types if necessary), which can then be evaluated.

例如:

var args = from arg in ((MethodCallExpression)expr.Body).Arguments
           let argAsObj = Expression.Convert(arg, typeof(object))
           select Expression.Lambda<Func<object>>(argAsObj, null)
                            .Compile()();

这显然会炸毁如果EX pression的身体不是一个方法调用前pression或任何参数的方法不能被评价为是(例如,如果它们依赖于参数前pression)。

This will obviously blow up if the expression's body is not a method-call expression or if any of the arguments to the method cannot be evaluated as is (e.g. if they depend on the argument to the expression).

很明显,你可以做一个更好的工作,如果你知道的参数类型的方法,事前。为了您的具体的例子,这应该工作:

Obviously, you can do a better job if you know the types of the arguments to the method beforehand. For your specific example, this should work:

var args = from arg in ((MethodCallExpression)expr.Body).Arguments               
           select Expression.Lambda<Func<int>>(arg, null)
                            .Compile()();

这篇关于获取EX pression树里面的方法参数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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