Obtaining method parameter values from inside expression trees

.net c# expression-trees

Question

With expression trees, I'm playing about, but I'm getting stuck.

I like to say this:

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

Where:

int b = 2;

public static int method()
{
    return 3;
}

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

I now need to know the method's name and the argument values for it. The method name is simple, but the hardest part is determining the parameter values. I am aware that I can parse them myself, but I would have to deal with every scenario.ConstantExpression , MemberExpression , MethodCallExpression perhaps more that I'm not aware of). I thus wondered whether there was a "generic" technique to determine their values. example 1, 2, 3.

1
6
4/28/2017 3:37:49 AM

Accepted Answer

You may access the defenses made byMethodCallExpression in doubt and produce compiledFunc<object> s from them, which may subsequently be evaluated, boxing value-types if required.

E.g.:

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

If the expression's body is not a method-call expression or if any of the method's parameters cannot be evaluated as-is, this will definitely go south (e.g. if they depend on the argument to the expression).

Of course, if you are aware of the sorts of arguments the method will accept in beforehand, you will perform better. This ought to work in your particular example:

var args = from arg in ((MethodCallExpression)expr.Body).Arguments               
           select Expression.Lambda<Func<int>>(arg, null)
                            .Compile()();
8
3/3/2011 1:56:09 PM

Popular Answer

Why not simply get all the arguments, compile them, and then run them? If they may be method calls, I don't understand how it would be able to retrieve all the data without executing.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow