[英]How to create a delegate for a reflected method at run time
我想创建一个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
。
这种委托 - 反射优化的关键在于您知道在编译时需要什么类型的委托。 如果你把它转换为类型Delegate
就像这样Delegate dlg =
你将不得不用Invoke方法调用它,这是相同的反射。
因此,您应该使用IL生成或表达式树来生成中性委托,如Func<object,object[],object>
。
另请阅读本文以便更好地理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.