【问题标题】:How to create a delegate for a reflected method at run time如何在运行时为反射方法创建委托
【发布时间】:2011-03-07 04:21:14
【问题描述】:

我想创建一个反射方法的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);
        }
    }
}

更新:

我在代码项目中找到的最接近的东西是 FastInvokeWrapper,但我仍在努力解决它,我不太明白 GetMethodInvoker 如何将反射方法绑定到 FastInvokeHandler .

【问题讨论】:

  • 为什么需要代理?
  • @codeulike,我想要 Delegate,这样我就可以调用该方法……并不是没有 Delegate 就无法调用它,而是 Delegate 允许以最快的速度调用反射方法。跨度>

标签: c# reflection dynamic delegates


【解决方案1】:

这种委托反射优化的全部意义在于您知道在编译时需要什么类型的委托。如果你将它转换成Delegate 这样的Delegate dlg = 类型,你将不得不使用 Invoke 方法来调用它,这是相同的反射。

因此,您应该使用 IL 生成或表达式树来生成中性委托,例如 Func&lt;object,object[],object&gt;

另请阅读this 以获得更好的理解。

【讨论】:

    猜你喜欢
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多