如何在运行时为反射方法创建委托

Kir*_*ril 5 c# reflection delegates dynamic

我想创建一个Delegate反射方法,但Delegate.CreateDelegate需要Type指定委托.是否有可能动态创建一个匹配任何功能的'委托'?

这是一个简单的例子:

class Functions
{
    public Functions()
    {

    }

    public double GPZeroParam()
    {
        return 0.0;
    }

    public double GPOneParam(double paramOne)
    {
        return paramOne;
    }

    public double GPTwoParam(double paramOne, double paramTwo)
    {
        return paramOne+paramTwo;
    }
}

static void Main(string[] args)
{
    Dictionary<int, List<Delegate>> reflectedDelegates = new Dictionary<int, List<Delegate>>();
    Functions fn = new Functions();
    Type typeFn = fn.GetType();
    MethodInfo[] methods = typeFn.GetMethods();

    foreach (MethodInfo method in methods)
    {
        if (method.Name.StartsWith("GP"))
        {
            ParameterInfo[] pi = method.GetParameters();

            if (!reflectedDelegates.ContainsKey(pi.Length))
            {
                reflectedDelegates.Add(pi.Length, new List<Delegate>());
            }

            // How can I define a delegate type for the reflected method at run time?
            Delegate dlg = Delegate.CreateDelegate(typeof(???), fn, method);
            reflectedDelegates[pi.Length].Add(dlg);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

我发现最接近的是代码项目中的FastInvokeWrapper,但我仍然试图绕过它并且我不太明白如何GetMethodInvoker将反射的方法绑定到FastInvokeHandler.

Vla*_*lad 1

这种类型的委托反射优化的重点是您在编译时知道需要什么类型的委托。如果将其转换为Delegate这样的类型Delegate dlg =,则必须使用 Invoke 方法来调用它,这是相同的反射。

因此,您应该使用 IL 生成或表达式树来生成中性委托,例如Func<object,object[],object>.

另请阅读本文以更好地理解。