c# - 如何在运行时为反射方法创建委托(delegate)

标签 c# reflection dynamic delegates

我想创建一个反射方法的 Delegate,但是 Delegate.CreateDelegate需要指定委托(delegate)的 Type。是否可以动态创建与所反射(reflect)的任何功能相匹配的“委托(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在代码项目上,但我仍在努力思考它,我不太明白 GetMethodInvoker 如何将反射的方法绑定(bind)到 FastInvokeHandler

最佳答案

这种类型的委托(delegate)反射优化的全部要点是您知道在编译时需要哪种类型的委托(delegate)。如果您将其转换为类型 Delegate像这样Delegate dlg =您将必须使用与反射相同的 Invoke 方法调用它。

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

另请阅读 this以便更好地理解。

关于c# - 如何在运行时为反射方法创建委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3099464/

相关文章:

c# - 通过泛型类中嵌套枚举的反射获取枚举值

java - 在 Java Swing 中动态添加 JPanel 到另一个 JPanel

c# - 除以零警告

c# - 如何动态调用具有已知参数基类型的委托(delegate)?

c# - 如何安排在 Hangfire 中的特定日期运行的作业

c# - InternalsVisibleTo - 如何防止某人创建具有相同名称的程序集并访问内部类或方法?

golang,从另一个变量创建一个变量

javascript - 欧拉项目#345 : Max sum matrix with unique path

Silverlight数据网格: Binding dynamically to an image source based on an object's property string?

c# - 如何在 C# 中为事件中心创建接收器以获取给定时间跨度的消息?