有没有办法在F#中按名称调用函数?给定一个字符串,我想从全局命名空间(或者,通常是给定的模块)中获取一个函数值,然后调用它.我已经知道了这个功能的类型.
我为什么要这样做?我正在努力解决没有--eval选项的fsi问题.我有一个脚本文件,定义了许多int - >()函数,我想执行其中一个.像这样:
fsianycpu --use:script_with_many_funcs.fsx --eval "analyzeDataSet 1"
Run Code Online (Sandbox Code Playgroud)
我的想法是编写一个蹦床脚本,如:
fsianycpu --use:script_with_many_funcs.fsx trampoline.fsx analyzeDataSet 1
Run Code Online (Sandbox Code Playgroud)
为了编写"trampoline.fsx",我需要按名称查找函数.
没有内置函数,但您可以使用.NET反射实现它.我们的想法是搜索当前程序集中可用的所有类型(这是编译当前代码的位置),并使用匹配的名称动态调用该方法.如果你在一个模块中有这个,你也必须检查类型名称.
// Some sample functions that we might want to call
let hello() =
printfn "Hello world"
let bye() =
printfn "Bye"
// Loader script that calls function by name
open System
open System.Reflection
let callFunction name =
let asm = Assembly.GetExecutingAssembly()
for t in asm.GetTypes() do
for m in t.GetMethods() do
if m.IsStatic && m.Name = name then
m.Invoke(null, [||]) |> ignore
// Use the first command line argument (after -- in the fsi call below)
callFunction fsi.CommandLineArgs.[1]
Run Code Online (Sandbox Code Playgroud)
当调用时,它会运行hello world:
fsi --use:C:\temp\test.fsx --exec -- "hello"
Run Code Online (Sandbox Code Playgroud)