Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting argument values of MethodCallExpression

How can I get the arguments values of a MethodCallExpression?

Today I do this way, but isn´t fast enough:

private static object GetArgumentValue(Expression element)
{
    LambdaExpression l = Expression.Lambda(Expression.Convert(element, element.Type));
    return l.Compile().DynamicInvoke();
}

This method get values from a Expression, but if I know that Expression always come from a MethodCallExpression.Arguments I can optimize it?

I think I can change first line to this, but I don't know if it works for all situations:

LambdaExpression l = Expression.Lambda(element);
like image 915
Felipe Pessoto Avatar asked Mar 25 '11 13:03

Felipe Pessoto


1 Answers

Cake

class Program
    {
        static void Main(string[] args)
        {
            Expression<Action<string>> action = a => Console.WriteLine("asdf");
            var mce = action.Body as MethodCallExpression;
            Console.WriteLine((mce.Arguments[0] as ConstantExpression).Value);
            Console.ReadKey();
        }
    }
like image 76
Sleeper Smith Avatar answered Sep 19 '22 16:09

Sleeper Smith