如何调用从MethodCallEx pression C#中的方法 [英] How to call the method from a MethodCallExpression in c#

查看:766
本文介绍了如何调用从MethodCallEx pression C#中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法调用前pression并尝试调用的方法。我想出了一个办法,但我有,因为不是所有的参数都与一个ConstantEx pression描述检索参数值的问题。

I have a method call expression and try to invoke the method. I figured out a way, but I have problems in retrieving the parameter values since not every argument is described with a ConstantExpression.

Expression<Action<T>> = t => t.DoSomething(Par0, Par1, Par2);
MethodCallExpression methodCallExpression = selector.Body 
                                               as MethodCallExpression;

// get the information which is needed to invoke the method from the provided 
// lambda expression.
MethodInfo methodInfo = methodCallExpression.Method;
object[] arguments = methodCallExpression.Arguments.OfType<ConstantExpression>()
                            .Select(p => p.Value).ToArray();

// invoke the expression on every item within the enumerable
foreach (TSource item in source)
{ 
    methodInfo.Invoke(item, arguments);
}

此外,我看到了一些其他的方式来调用的方法,现在我不知道什么是正确的方式来做到这一点。

Additionally, I have seen some other ways to invoke the method, now I'm not sure what is the right way to do it.

var func = expression.Compile();
var success = func.Invoke();

我的问题是,我怎么能检索 methodCallEx pression.Arguments 方法参数的值?

或者是有一个更简单的方法来实现我的目标?

Or is there an easier way to achieve my goal?

推荐答案

您不必担心检索参数和调用的MethodInfo自己,你可以让.NET为你做它。所有你需要做的就是创建一个包含该方法的lambda EX pression。

You don't need to worry about retrieving the arguments and calling the MethodInfo yourself, you can let .NET do it for you. All you need to do is create a Lambda expression containing that method.

如:

MethodCallExpression expression = GetExpresionSomeHow();
object result = Expression.Lambda(expression).Compile().DynamicInvoke();

这就是我如何处理我的LINQ提供程序的嵌套查询反正。

That's how I deal with nested queries in my Linq provider anyway.

编辑:其实,它看起来像你可能已经有一个LambdaEx pression在选择的变量。在这种情况下,你应该能够只是编译并直接调用它:

Actually, it looks like you might already have a LambdaExpression in the selector variable. In that case, you should be able to just compile and invoke it directly:

object result = selector.Compile().DynamicInvoke();

这篇关于如何调用从MethodCallEx pression C#中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆