c# - Call Func<> with argument of type object -
i have (for instance) func<int, int> want call usual, except parameter of type object rater int. know exact type of func , argument @ runtime, because func created using expression trees , accessed dynamic variable. (simplified) code example:
using system.linq.expressions; namespace funcexample { class program { static void main(string[] args) { object myfunc = createfunc(); // return // func<int, int>, may return // different func<> depending on // arguments etc. object result = getfromfunc(5, myfunc); } public static object createfunc() { lambdaexpression expr = expression.lambda( /* * create expression */ ); return expr.compile(); } public static object getfromfunc(object arg, object func) { dynamic dynfunc = func; return dynfunc(arg); // <------- throws exception } } } how can make code convert arg integer or whatever type argument is? tried making generic method casts object type , invoking through reflection this:
public static t ast<t>(object n) { return (t)n; } for getfromfunc:
methodinfo con = typeof(program).getmethod("ast").makegenericmethod(func.gettype().getgenericarguments()[0]); return dfunc(con.invoke(null, new[] { value })); but methodinfo.invoke returns object. ideas on how make sure argument has correct type?
you're using dynamic, why not use dynamic?
return dynfunc((dynamic)arg); this makes sure arg's runtime type gets used determining whether it's appropriate argument.
Comments
Post a Comment