I want to emit a method that returns a Func<>. Inside this method I have to create a delegate or a lambda expression which exactly serves the return type.
Altoget
The first problem is that Func<...>
doesn't exist - you'd need to code to Func<>
, Func<,>
, Func<,,>
, Func<,,,>
separately.
Now; I understand the code, but I'm not sure what the scenario is that you are trying to solve... can you clarify? There are probably better options...
If it is as complex as it sounds, a custom Expression
is probably the most appropriate option (far simpler than Reflection.Emit
).
This works, for example...
static Delegate MissingFunc(Type result, params Type[] args)
{
int i = 0;
var param = Array.ConvertAll(args,
arg => Expression.Parameter(arg, "arg" + i++));
var asObj = Array.ConvertAll(param,
p => Expression.Convert(p, typeof(object)));
var argsArray = Expression.NewArrayInit(typeof(object), asObj);
var body = Expression.Convert(Expression.Call(
null, typeof(Program).GetMethod("Resolve"),
argsArray), result);
return Expression.Lambda(body, param).Compile();
}
static void Main()
{
var func2 = MissingFunc(typeof(string), typeof(int), typeof(float));
}
public static object Resolve( params object[] args) {
throw new NotImplementedException();
}