1

我正在尝试创建一个表达式树,其中包含对某个模块上的 F# 函数的函数调用。但是,我遗漏了一些东西,因为System.Linq.Expressions.Expression.Call()辅助函数找不到我提供的函数。

Call() 调用给出了InvalidOperationException:“类型 'TestReflection.Functions' 上没有方法 'myFunction' 与提供的参数兼容。

如果有人可以提示我做错了什么,那将非常有帮助。

请看下面的代码:

namespace TestReflection

open System.Linq.Expressions

module Functions =
    let myFunction (x: float) =
        x*x

    let assem = System.Reflection.Assembly.GetExecutingAssembly()
    let modul = assem.GetType("TestReflection.Functions")
    let mi = modul.GetMethod("myFunction")
    let pi = mi.GetParameters()

    let argTypes =
        Array.map 
            (fun (x: System.Reflection.ParameterInfo) -> x.ParameterType) pi

    let parArray = 
        [| (Expression.Parameter(typeof<float>, "a") :> Expression); |]
    let ce = Expression.Call(modul, mi.Name, argTypes, parArray)

    let del = (Expression.Lambda<System.Func<float, float>>(ce)).Compile()

printf "%A" (Functions.del.Invoke(3.5))

问候, 里卡德

4

1 回答 1

3

的第三个参数Expression.Call是泛型类型参数的数组 - 你的方法不是泛型的,所以应该是null. 您还需要将“a”参数传递给Expression.Lambda

    let a = Expression.Parameter(typeof<float>, "a")
    let parArray = [| (a :> Expression); |]
    let ce = Expression.Call(modul, mi.Name, null, parArray)

    let del = (Expression.Lambda<System.Func<float, float>>(ce, a)).Compile()
于 2009-10-12T19:52:27.217 回答