我可以在f#中按名称调用函数吗? [英] Can I call a function by name in f#?

查看:66
本文介绍了我可以在f#中按名称调用函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以在F#中按名称调用函数?给定一个字符串,我想从全局名称空间(或者通常是给定的模块)中提取一个函数值,然后调用它.我已经知道函数的类型.

Is there any way to call a function by name in F#? Given a string, I want to pluck a function value from the global namespace (or, in general, a given module), and call it. I know the type of the function already.

我为什么要这样做?我正在尝试解决fsi没有--eval选项的问题.我有一个脚本文件,该文件定义了许多int->()函数,并且我想执行其中一个.像这样:

Why would I want to do this? I'm trying to work around fsi not having an --eval option. I have a script file that defines many int->() functions, and I want to execute one of them. Like so:

fsianycpu --use:script_with_many_funcs.fsx --eval "analyzeDataSet 1"

我的想法是写一个蹦床脚本,例如:

My thought was to write a trampoline script, like:

fsianycpu --use:script_with_many_funcs.fsx trampoline.fsx analyzeDataSet 1

要编写"trampoline.fsx",我需要按名称查找该函数.

In order to write "trampoline.fsx", I'd need to look up the function by name.

推荐答案

对此没有内置函数,但是您可以使用.NET反射实现它.这个想法是搜索当前程序集中所有可用的类型(这是当前代码的编译位置),并用匹配的名称动态调用该方法.如果您在模块中有此名称,则还必须检查类型名称.

There is no built-in function for this, but you can implement it using .NET reflection. The idea is to search through all types available in the current assembly (this is where the current code is compiled) and dynamically invoke the method with the matching name. If you had this in a module, you'd have to check the type name too.

// 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]

当被以下人员调用时,它将运行世界:

This runs hello world when called by:

fsi --use:C:\temp\test.fsx --exec -- "hello"

这篇关于我可以在f#中按名称调用函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆