Howto emit a delegate or lambda expression

前端 未结 1 780
一整个雨季
一整个雨季 2021-01-03 09:56

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

相关标签:
1条回答
  • 2021-01-03 10:04

    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();
    }
    
    0 讨论(0)
提交回复
热议问题