How to call the method from a MethodCallExpression in c#

后端 未结 5 1690
生来不讨喜
生来不讨喜 2020-12-29 06:33

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 describ

5条回答
  •  再見小時候
    2020-12-29 07:01

    If you want to compile your expression.call into a Action or Func, this is how you do:

    var method = typeof(MyType).GetMethod(nameof(MyType.MyMethod), BindingFlags.Public | BindingFlags.Static);
    var parameter = Expression.Parameter(typeof(string), "s");
    var call = Expression.Call(method, parameter);
    var lambda = Expression.Lambda>(call, call.Arguments.OfType());
    var func = lambda.Compile();
    int result = func("sample string input");
    

    This allows you to simply do func.Invoke("mystring") or func("my string");

    The secret here is you need to pass the same parameters you used when creating the Expression.Call, otherwise you get an error of type "InvalidOperationException" variable 's' of type 'System.String' referenced from scope '', but it is not defined.

提交回复
热议问题