使用ILGenerator创建委托

时间:2017-01-02 14:49:44

标签: c# delegates ilgenerator

如何使用ILGenerator.Emit(而不是LambdaExpression.Compile?动态创建具有未知参数的未知目标上调用的未知MethodInfo的委托,而不是LambdaExpression.Compile?因为我正在尝试找到更高性能的解决方案)

public void CreateDelegate(MethodInfo mi, object target, object[] arguments)
{
    var method = new DynamicMethod("Temp", typeof(void), Type.EmptyTypes);
    var generator = method.GetILGenerator();
    // Make the method call mi on target with arguments
    // ...
    method.CreateDelegate(typeof(Action));
}

1 个答案:

答案 0 :(得分:0)

也许您正在寻找类似的东西? 如果未知,则表示任何:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;

namespace Platform.Reflection
{
    public static class DelegateHelpers
    {
        public static TDelegate CompileOrDefault<TDelegate>(Action<ILGenerator> emitCode)
            where TDelegate : Delegate
        {
            var @delegate = default(TDelegate);
            try
            {
                var delegateType = typeof(TDelegate);
                var invoke = delegateType.GetMethod("Invoke");
                var returnType = invoke.ReturnType;
                var parameterTypes = invoke.GetParameters().Select(s => s.ParameterType).ToArray();
                var dynamicMethod = new DynamicMethod(Guid.NewGuid().ToString(), returnType, parameterTypes);
                var generator = dynamicMethod.GetILGenerator();
                emitCode(generator);
                @delegate = (TDelegate)dynamicMethod.CreateDelegate(delegateType);
            }
            catch (Exception exception)
            {
                // ignore
            }
            return @delegate;
        }
    }
}

或者,您可以仅引用Platform.Reflection(0.1.0版或更高版本)NuGet程序包。并使用Platform.Reflection.DelegateHelpers。