开发者

how to get parameter names from an expression tree?

开发者 https://www.devze.com 2022-12-18 06:58 出处:网络
I have a expression of this type: Expression<Action<T>> expression how do I get the parameters names from this expression (optional: and values) ?

I have a expression of this type:

Expression<Action<T>> expression

how do I get the parameters names from this expression (optional: and values) ?

example:

o => o.Method("value1", 2, new Object());

names coul开发者_C百科d be str_par1, int_par2, obj_par3


Expression<Action<Thing>> exp = o => o.Method(1, 2, 3);
var methodInfo = ((MethodCallExpression)exp.Body).Method;
var names = methodInfo.GetParameters().Select(pi => pi.Name);


You can get the parameter names from the Parameters property.

For example:

    Expression<Action<string, int>> expr = (a, b) => (a + b).ToString();
var names = expr.Parameters.Select(p => p.Name);  //Names contains "a" and "b"

For the second part, lambda expressions are just uncompiled functions.
Their parameters don't have values until you compile the expression and call the delegate with some values.

If you take the lambda expression i => i.ToString(), where are there any parameter values?


The parameters for Method? Get the MethodInfo from the expression (at a guess, MethodCallExpression.Method), and then use MethodBase.GetParameters() to get the parameters. (ParameterInfo has various useful properties, including Name).


How do I get the parameters names from this expression ?

expression.Parameters[0].Name

For your future reference, the documentation is here:

http://msdn.microsoft.com/en-us/library/bb359453.aspx

(optional: and values) ?

This doesn't make any sense to me. Can you explain what you mean by "and values"?


I actually wanted the names of the parameters of the method o => o.Method(par1, par2, par3)

You have some belief that we're psychic, perhaps.

Anyway, moving on.

I actually wanted the names of the parameters of the method o => o.Method(par1, par2, par3)

The name of the first formal parameter is:

(expression.Body as MethodCallExpression).Method.GetParameters()[0].Name

The expression which is the first argument is

(expression.Body as MethodCallExpression).Arguments[0]

For your future reference, the documentation is here:

http://msdn.microsoft.com/en-us/library/system.linq.expressions.methodcallexpression.arguments.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消