I'm writing a function that will be passed a lambda expression, and I want to convert the parameters that the lambda takes to an object array.
The only way I've been able to do it is with code I borrowed from here, and my function looks something like this:
public class MyClassBase<T> where T : class
{
protected void DoStuff(Expression<Action<T>> selector)
{
ReadOnlyCollection<Expression> methodArgumentsCollection = (selector.Body as MethodCallExpression).Arguments;
object[] methodArguments = methodArgumentsCollection.Select(c => Expression.Lambda(c is UnaryExpression ?
((UnaryExpression)c).Operand : c)
.Compile()
.DynamicInvoke())
.ToArray();
// do more stuff with methodArguments
}
}
interface IMyInterface
{
void MethodSingleParam(string param1);
}
class MyClass : MyClassBase<IMyInterface>
{
void MakeCall()
{
DoStuff(x => x.MethodSingleParam("abc"));
}
}
Is there a neater way of doing this? It seems like overkill having to compile and invoke the lambda when all I want is the parameter values.