Reputation: 71288
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 could be str_par1, int_par2, obj_par3
Upvotes: 10
Views: 6531
Reputation: 660493
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
Upvotes: 2
Reputation: 1503419
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
).
Upvotes: 3
Reputation: 233387
Expression<Action<Thing>> exp = o => o.Method(1, 2, 3);
var methodInfo = ((MethodCallExpression)exp.Body).Method;
var names = methodInfo.GetParameters().Select(pi => pi.Name);
Upvotes: 17
Reputation: 888167
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?
Upvotes: 4
Reputation: 660493
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"?
Upvotes: 2