When I have this,
public static object Create()
{
return new object();
}
this works:
var m = typeof(Class).GetMethod("Create");
var e = Expression.Call(m);
Func<object> f = Expression.Lambda<Func<object>>(e).Compile();
But when I have this,
public static object Create(Type t)
{
return new object();
}
this fails:
var m = typeof(Class).GetMethod("Create");
var e = Expression.Call(m, Expression.Parameter(typeof(Type)));
var t = Expression.Parameter(typeof(Foo));
Func<object> f = Expression.Lambda<Func<object>>(e, t).Compile();
I get An unhandled exception of type 'System.ArgumentException' occurred in System.Core.dll. Additional information: Incorrect number of parameters supplied for lambda declaration. The parameter t
is just expression for a dummy type Foo
. I think that's irrelevant. Where have I gone wrong here?
The problem is that you've said you want to use a parameter - but then you're not actually providing anywhere to specify it. You were creating two ParameterExpression
s of different types, and then trying to convert the result into a Func<object>
- which doesn't have any parameters at all. You want something like:
var m = typeof(Class).GetMethod("Create");
var p = Expression.Parameter(typeof(Type), "p");
var e = Expression.Call(m, p);
Func<Type, object> f = Expression.Lambda<Func<Type, object>>(e, p).Compile();
Note that the same ParameterExpression
is used in the argument list for both theExpression.Call
method and the Expression.Lambda
methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With