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