【发布时间】: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