public FastMethodInfo(MethodInfo methodInfo) { var instanceExpression = Expression.Parameter(typeof(object), "instance"); var argumentsExpression = Expression.Parameter(typeof(object[]), "arguments"); var argumentExpressions = new List <Expression>(); var parameterInfos = methodInfo.GetParameters(); for (var i = 0; i < parameterInfos.Length; ++i) { var parameterInfo = parameterInfos[i]; argumentExpressions.Add(Expression.Convert(Expression.ArrayIndex(argumentsExpression, Expression.Constant(i)), parameterInfo.ParameterType)); } var callExpression = Expression.Call(!methodInfo.IsStatic ? Expression.Convert(instanceExpression, methodInfo.ReflectedType) : null, methodInfo, argumentExpressions); if (callExpression.Type == typeof(void)) { var voidDelegate = Expression.Lambda <VoidDelegate>(callExpression, instanceExpression, argumentsExpression).Compile(); _delegate = (instance, arguments) => { voidDelegate(instance, arguments); return(null); }; } else { _delegate = Expression.Lambda <ReturnValueDelegate>(Expression.Convert(callExpression, typeof(object)), instanceExpression, argumentsExpression).Compile(); } }
public MethodInvoker(MethodInfo methodInfo, Type[] parameterTypes, Type returnType) { ParameterTypes = parameterTypes; ReturnsResult = returnType != null; ReturnType = returnType; _delegate = BuildDelegate(methodInfo); if (ReturnsResult) { TaskReturnPropertyInfo = methodInfo.ReturnType.GetTypeInfo().GetProperty("Result"); } }
private static void DelegatesAndAnonymousMethods() { var demoDelegate = new DemoDelegate(); var simpleDelegate = new SimpleDelegate(demoDelegate.MethodA); ReturnValueDelegate returnValueDelegate = demoDelegate.MethodB; TwoParametersDelegate twoParametersDelegate = demoDelegate.MethodC; Console.WriteLine("Delegates -----------------------------------------------------------------"); simpleDelegate(); returnValueDelegate(); twoParametersDelegate("Michael", 43); demoDelegate.Repeat3Times(simpleDelegate); demoDelegate.Repeat3Times2(delegate(string n, int a) { Console.WriteLine("delegate({0}, {1})", n, a); }); Console.WriteLine(); }