获取MethodCallExpression的参数值

时间:2011-03-25 13:11:39

标签: c# lambda expression-trees

如何获取MethodCallExpression的参数值?

今天我这样做,但还不够快:

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

此方法从Expression获取值,但如果我知道Expression总是来自MethodCallExpression.Arguments,我可以优化它吗?

我想我可以改变第一行,但我不知道如果能适用于所有情况:

    LambdaExpression l = Expression.Lambda(element);

3 个答案:

答案 0 :(得分:3)

蛋糕

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();
        }
    }

答案 1 :(得分:2)

我会尝试这个来返回对象:

private static object _getValue(MethodCallExpression expression)
{
    var objectMember = Expression.Convert(expression, typeof(object));

    var getterLambda = Expression.Lambda<Func<object>>(objectMember);

    var getter = getterLambda.Compile();

    return getter();
}

比调用以下内容快得多:

LambdaExpression l = Expression.Lambda(Expression.Convert(element, element.Type));
return l.Compile().DynamicInvoke();

答案 2 :(得分:2)

这对我有用:

private static object GetArgumentValue(Expression element)
{
    if (element is ConstantExpression)
    {
        return (element as ConstantExpression).Value;
    }

    var l = Expression.Lambda(Expression.Convert(element, element.Type));
    return l.Compile().DynamicInvoke();
}

它将OP's original solutionSleeper Smith's Answer合并。