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

5
我想创建一个反射方法的Delegate,但是Delegate.CreateDelegate要求指定委托的Type。是否可能动态创建与反映的任何函数匹配的“Delegate”?
这里有一个简单的例子:
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);
        }
    }
}

更新:

我找到的最接近的东西是这个FastInvokeWrapper在code-project上,但我仍然试图理解它,我不太明白GetMethodInvoker如何将反射方法绑定到FastInvokeHandler


为什么需要委托? - codeulike
@codeulike,我想要Delegate,这样我就可以调用方法了...不是说没有Delegate就不能调用它,但Delegate允许最快速地调用反射方法。 - Kiril
1个回答

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

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

此外,请阅读this以获得更好的理解。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接