以下代码尝试创建一个 Func 委托(delegate),将原始 func 参数类型转换为另一种类型。
public static Delegate Convert<T1, R>(this Func<T1, R> func, Type argType)
{
var param = Expression.Parameter(argType);
var convertedParam = new Expression[] { Expression.Convert(param, typeof(T1))};
var call = Expression.Convert(
func.Target == null || func.Target is Closure
? Expression.Call(func.Method, Expression.Constant(func.Target), convertedParam[0])// this path causes the error
: Expression.Call(Expression.Constant(func.Target), func.Method, convertedParam), typeof(R));
var delegateType = typeof(Func<,>).MakeGenericType(argType, typeof(R));
var lambda = Expression.Lambda(delegateType, call, param);
return lambda.Compile();// BUG: 'MethodInfo must be a runtime MethodInfo object.
}
当 Func 包含作为目标的闭包时,我的问题就开始了,lambda.Compile() 错误说“方法信息必须是运行时 MethodInfo 对象”,我怀疑这是因为该方法是静态的。
有人可以向我解释我做错了什么吗?为什么?我显然对表达式的理解不够好,无法自行解决这个问题。
提前致谢。
最佳答案
你应该调用Expression.Invoke
,这将直接调用委托(delegate)。
将其传递给 Expression.Constant(func)
。
关于c# - 如何处理表达式树中的闭包和静态方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46960963/