I have below code that is a pseudo-code. I want to make this function can accept a Expresstion type, compile this expression and invoke it with proper parameters.
public static void f<T>(Expression<T> exp, params dynamic[] d)
{
Console.WriteLine("begin");
exp.Compile().Invoke(d[0],d[1].....);//this is pseudo-code
Console.WriteLine("end");
}
I'm sure the T is an Action type. (T can be Action
,Action<int>
,etc.). The parameter d
is a array of dynamic type, which is sent to invoke.
But I don't know how to finish the code. I'm sure that's not easy to implement it. Perhaps it can't be true in c#
You can't use
Invoke
unless you know the exact signature. You can, however, useDynamicInvoke
, for example:Note that the
dynamic
in the above serves no purpose -d
could just as well beobject[]
.The other, slightly more complicated, approach - would be to compile it as a
Func<object[]>
, and re-write the expression (ExpressionVisitor
) to replace "parameter n" (from the originalexp
) withp[n]
, wherep
is a singleParameterExpression
andn
is aConstantExpression
ofn
. This might be advantageous if you were going to store and aggressively re-use the compiled lambda. But in your specific scenario you are compiling per call, so this would have no benefit.Here's an example, but this is mainly intended for later readers with similar scenarios, but where the compiled delegate is re-used; the "advantage" of this re-writing is that it avoids the performance impact of
Delegate.DynamicInvoke
, while retaining theobject[] => object
signature ofDelegate.DynamicInvoke
; but this will only be useful if the delegate is being used multiple times. At the moment (compiled per call) most of the "work" here is going to be in the expression-compile and JIT-compile.And then:
or: