【发布时间】:2012-02-29 19:07:26
【问题描述】:
您好,我正在尝试创建一个函数,该函数动态创建一个委托,该委托具有与它作为参数接收的 MethodInfo 相同的返回值和相同的参数,而且相同的参数名称非常重要!
到目前为止,我所做的是创建一个函数,该函数返回一个 lambda,它接收相同的参数类型并具有与 MethodInfo 相同的返回值,但它没有参数名称:
static void Example()
{
Person adam = new Person();
MethodInfo method = typeof(Person).GetMethod("Jump");
Delegate result = CreateDelegate(adam, method);
result.DynamicInvoke((uint)4, "Yeahaa");
}
private static Delegate CreateDelegate(object instance, MethodInfo method)
{
var parametersInfo = method.GetParameters();
Expression[] expArgs = new Expression[parametersInfo.Length];
List<ParameterExpression> lstParamExpressions = new List<ParameterExpression>();
for (int i = 0; i < expArgs.Length; i++)
{
expArgs[i] = Expression.Parameter(parametersInfo[i].ParameterType, parametersInfo[i].Name);
lstParamExpressions.Add((ParameterExpression)expArgs[i]);
}
MethodCallExpression callExpression = Expression.Call(Expression.Constant(instance), method, expArgs);
LambdaExpression lambdaExpression = Expression.Lambda(callExpression, lstParamExpressions);
return lambdaExpression.Compile();
}
private class Person
{
public void Jump(uint height, string cheer)
{
Console.WriteLine("Person jumped " + height + " "+ cheer);
}
}
有人对我如何做到这一点有任何建议吗? 为了清楚起见,我关心参数名称的原因是我可以使用参数名称激活委托,所以我可以这样称呼它 (cheer="YAY!', height=3) (我的应用程序与 Python 集成,这就是我在没有 DynamicInvoke 的情况下能够做到的方式,这也是参数名称如此重要的原因 以及为什么我写了'='而不是':')
【问题讨论】:
标签: c# dynamic parameters delegates expression-trees