我想创建一个反射方法的
这里有一个简单的例子:
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
。