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

标签 c# lambda delegates closures expression-trees

以下代码尝试创建一个 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/

相关文章:

c# - IdentityServer4 PostLogoutRedirectUri 空

c# - ORDER BY 给出错误的命令

python - 了解 lambda 在 python 中的排序功能

android - Kotlin-内联参数回调的非法使用

java - 读取 csv 文件并在 Lambda (Java8) 中过滤特定列

c# - 当变量更改时生成事件以从代码类发送以形成类 c#

c# - Unity C# 中的泛型

c# - InternalsVisibleTo 使用 "Company"属性而不是 "Assembly Name"?

iphone - 使用协议(protocol)和委托(delegate)在 View 之间传递数据

c# - 使用委托(delegate)在 C# 中实现的观察者模式?