Saturday, 15 August 2015

c# - Converting MethodInfo.Invoke to Expression.Call -



c# - Converting MethodInfo.Invoke to Expression.Call -

in project have next 2 methods used phone call other methods variable number , types of arguments:

private static object invokemethod(methodinfo method, mytargetclass target, object[] initialargs, object[] additionalargs) { object result = null; var methodparams = method.getparameters(); if (methodparams.length == 0) { result = method.invoke(target, null); } else { var args = collectarguments(method, initialargs, paramargs); // collect arguments default values missing ones , invoke method result = method.invoke(target,args); } homecoming result; } private static object[] collectarguments(methodinfo method, object[] initialargs, object[] paramargs) { list<object> allargs = new list<object>(); allargs.addrange(initialargs); // append param style args if (paramargs != null) allargs.addrange(paramargs); // have plenty arguments? int missing = method.getparameters().length - allargs.count; if (missing < 0) throw new invalidoperationexception(string.format("too many arguments passed method {0}", method.name)); (int = 0; < missing; i++) { // parameters after mandatory should optional default values, pass them allargs.add(type.missing); } homecoming allargs.toarray(); }

my invokemethod called often, optimize it. caching methodinfo references. methods phone call have custom attribute , collect methods in dictionary upon application startup. managed cache lambda expressions constructors of mytargetclass derived classes , cache lambda expressions method calls.

i have found examples how create lambda expressions expression.call, problem don't know how deal variable arguments, include default values (that's why adding type.missing) , there might ref arguments.

there additional rules methods want invoke (omitted brevity), methods might this:

mymethod1(int a, long b = 2) mymethod2(ref long a, ref long b, string something)

i know special cases ref arguments, after method.invoke collect ref variables back:

a = (long)allargs[0]; b = (long)allargs[1];

where , b passed ref outside.

how accomplish same functionality using expression.call? how pass variable count of arguments , how ref values?

c# lambda invoke precompiled

No comments:

Post a Comment