与调用参数

问题描述:

我需要动态数量MethodCallExpression调用下面:与调用参数

public MethodCallExpression CreateLazyMethod(object instance, MethodBase foundMethodInfo) 
{ 
    var orderedParameters = MethodParametersEvaluator.OrderParameters(foundMethodInfo.GetParameters()); 
    var paramExpressions = orderedParameters.Select(x => (Expression)Expression.Parameter(x.GetType())).ToArray(); 
    return Expression.Call((MethodInfo)foundMethodInfo, paramExpressions); 
} 

和解决在运行一样东西时的参数:

var callabel = CreateLazyMethod(instance, foundMethodInfo); 
var runtimeEvaluatedParamsList=new object[]{1,654,}; 
callable.Invoke(runtimeEvaluatedParamsList); 

任何解决方案?

您可以将它作为object[]发送,然后在方法生成期间使用特定项目。

基本上低于"Test Long String".Substring(5);代码会产生这样的方法:

object DynamicMethod(object[] params) 
{ 
    return "Test Long String".Substring((int)params[0]); 
} 

缺点是结果,而params的对象,因此它会产生不必要的拳击\拆箱操作,但如果你知道的签名,那么你就可以写通用将使用特定类型的实现。

示例代码:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Linq.Expressions; 
using System.Reflection; 

public class Program 
{ 
    public static void Main(string[] args) 
    { 
     // test non static method with result 
     string test = "Test String"; 
     MethodInfo method = typeof(string).GetMethod("Substring", BindingFlags.Public | BindingFlags.Instance, null, new Type[]{typeof(int)},null); 
     Func<object[], object> lazyMethod = CreateLazyMethodWithResult(test, method); 
     object result = lazyMethod(new object[] { 5 }); 
     Console.WriteLine(result); 
     Console.WriteLine(); 

     // test static method with no result 
     var staticMethod = typeof(Program).GetMethod("StaticMethod", BindingFlags.Static | BindingFlags.Public); 
     var staticAction = CreateLazyStaticMethodWithNoResult(staticMethod); 

     staticAction(new object[]{"Test message"}); 
     Console.WriteLine(); 

     //test static method with result 
     var staticMethodWithResult = typeof(Program).GetMethod("StaticMethodWithResult", BindingFlags.Static | BindingFlags.Public); 
     var staticActionWithResult = CreateLazyStaticMethodWithResult(staticMethodWithResult); 

     Console.WriteLine(staticActionWithResult(new object[] { "Test message" })); 
     Console.WriteLine(); 

     // sample with constructor 
     var constructorCall = typeof(TestClass).GetConstructors().First(); 
     var constructorAction = GenerateLazyConstructorCall(constructorCall); 

     var createdObject = constructorAction(new object[] { "Test message" }); 

     Console.WriteLine("Created type is " + createdObject.GetType().FullName); 
    } 

    //Test class 
    public class TestClass 
    { 
     public TestClass(string message) 
     { 
      Console.WriteLine("----Constructor is called with message - " + message); 
     } 
    } 

    public static void StaticMethod(string message) 
    { 
     Console.WriteLine("----Static method is called with " + message); 
    } 

    public static string StaticMethodWithResult(string message) 
    { 
     Console.WriteLine("----Static method with result is called with " + message); 
     return "Hello from static method"; 
    } 

    public static Func<object[], object> CreateLazyMethodWithResult(object instance, MethodInfo method) 
    { 
     ParameterExpression allParameters; 
     var methodCall = GenerateCallExpression(instance, method, out allParameters); 
     var lambda = Expression.Lambda<Func<object[], object>>(methodCall, allParameters); 
     return lambda.Compile(); 
    } 

    public static Action<object[]> CreateLazyMethodWithNoResult(object instance, MethodInfo method) 
    { 
     ParameterExpression allParameters; 
     var methodCall = GenerateCallExpression(instance, method, out allParameters); 
     var lambda = Expression.Lambda<Action<object[]>>(methodCall, allParameters); 
     return lambda.Compile(); 
    } 

    public static Func<object[], object> CreateLazyStaticMethodWithResult(MethodInfo method) 
    { 
     ParameterExpression allParameters; 
     var methodCall = GenerateCallExpression(null, method, out allParameters); 
     var lambda = Expression.Lambda<Func<object[], object>>(methodCall, allParameters); 
     return lambda.Compile(); 
    } 

    public static Action<object[]> CreateLazyStaticMethodWithNoResult(MethodInfo method) 
    { 
     ParameterExpression allParameters; 
     var methodCall = GenerateCallExpression(null, method, out allParameters); 
     var lambda = Expression.Lambda<Action<object[]>>(methodCall, allParameters); 
     return lambda.Compile(); 
    } 


    /// <summary> 
    /// Generate expression call 
    /// </summary> 
    /// <param name="instance">If instance is NULL, then it method will be treated as static method</param> 
    private static MethodCallExpression GenerateCallExpression(object instance, MethodBase method, out ParameterExpression allParameters) 
    { 
     var parameters = GenerateParameters(method, out allParameters); 

     var methodInfo = method as MethodInfo; 
     // it's non static method 
     if (instance != null) 
     { 
      var instanceExpr = Expression.Convert(Expression.Constant(instance), instance.GetType()); 
      return Expression.Call(instanceExpr, methodInfo, parameters.ToArray()); 
     } 

     // it's static method 
     return Expression.Call(methodInfo, parameters.ToArray()); 
    } 

    public static Func<object[], object> GenerateLazyConstructorCall(ConstructorInfo constructor) 
    { 
     ParameterExpression allParameters; 
     var parameters = GenerateParameters(constructor, out allParameters); 

     var newExpr = Expression.New(constructor, parameters.ToArray()); 
     var lambda = Expression.Lambda<Func<object[], object>>(newExpr, allParameters); 

     return lambda.Compile(); 
    } 

    private static List<Expression> GenerateParameters(MethodBase method, out ParameterExpression allParameters) 
    { 
     allParameters = Expression.Parameter(typeof(object[]), "params"); 
     ParameterInfo[] methodMarameters = method.GetParameters(); 
     List<Expression> parameters = new List<Expression>(); 
     for (int i = 0; i < methodMarameters.Length; i++) 
     { 
      var indexExpr = Expression.Constant(i); 
      var item = Expression.ArrayIndex(allParameters, indexExpr); 
      var converted = Expression.Convert(item, methodMarameters[i].ParameterType); 
      parameters.Add(converted); 
     } 

     return parameters; 
    } 
} 

实际的工作例如:https://dotnetfiddle.net/lHB2kE

UPDATE 我更新的代码样本调用方法和构造函数:

  1. 实例方法没有返回对象
  2. 实例方法有一些返回对象
  3. 没有返回对象的静态方法
  4. 一些返回对象的静态方法
  5. 样品的构造使用
+0

:感谢名单我怎么能像调用构造函数:'ctor.Invoke(新对象[] {10})' – Mohsen 2014-10-29 10:28:06

+0

:我怎样才能调用静态(这得到我:'System.Boolean'类型的表达式不能用于返回类型'System.Object') – Mohsen 2014-10-29 10:59:06

+0

我已经更新了答案样本静态方法。如果你需要调用返回'Boolean'的静态方法,那么你可以在'Main'方法中检查'CreateLazyStaticMethodWithResult'方法和使用它的样本。 – 2014-10-29 11:26:58