C# 如何在表达式树中处理闭包和静态方法调用?

C# 如何在表达式树中处理闭包和静态方法调用?,c#,lambda,delegates,closures,expression-trees,C#,Lambda,Delegates,Closures,Expression Trees,以下代码尝试创建一个Func委托,该委托将从原始Func参数类型转换为其他类型 public static Delegate Convert<T1, R>(this Func<T1, R> func, Type argType) { var param = Expression.Parameter(argType); var convertedParam = new Expression[] { Expression.Conve

以下代码尝试创建一个Func委托,该委托将从原始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-Func,类型argType)
{
var param=Expression.Parameter(argType);
var convertedParam=新表达式[]{Expression.Convert(param,typeof(T1))};
var call=Expression.Convert(
func.Target==null | | func.Target是闭包
?Expression.Call(func.Method,Expression.Constant(func.Target),convertedParam[0])//此路径导致错误
:Expression.Call(Expression.Constant(funct.Target)、funct.Method、convertedParam、typeof(R));
var delegateType=typeof(Func).MakeGenericType(argType,typeof(R));
var lambda=Expression.lambda(delegateType,call,param);
返回lambda.Compile();//BUG:'MethodInfo必须是运行时MethodInfo对象。
}
当Func包含一个闭包作为目标时,问题就开始了,lambda.Compile()bug说“方法信息必须是运行时MethodInfo对象”,我怀疑这是因为该方法是静态的

有人能给我解释一下我做错了什么吗?为什么?很明显,我对表达式的理解不够好,无法自己解决这个问题

提前谢谢。

您应该打电话,这将直接呼叫代表

传递您应该调用的
Expression.Constant(func)
,它将直接调用委托


传递它
Expression.Constant(func)

非常感谢,我刚刚尝试了它,它似乎很有效…再次感谢!非常感谢,我刚刚试了一下,似乎很管用……再次感谢!