如何获取应该是 F# 代码的文本字符串,并将其解析为 F# 代码,以在屏幕上打印结果?
我猜测这个问题可以通过 .NET 中的一个功能来解决,因此可以通过 F# 本身或 C# 来完成。
这可能以什么方式解决tryfsharp.org http://www.tryfsharp.org/Tutorials.aspx?
可以使用实现所需的F# CodeDom 提供程序 http://fsharppowerpack.codeplex.com/。下面的最小可运行代码片段演示了所需的步骤。它从字符串中获取任意可能正确的 F# 代码,并尝试将其编译为汇编文件。如果成功,那么它会从以下位置加载刚刚合成的程序集:dll
文件并从那里调用已知函数,否则它会显示编译代码时出现的问题。
open System
open System.CodeDom.Compiler
open Microsoft.FSharp.Compiler.CodeDom
// Our (very simple) code string consisting of just one function: unit -> string
let codeString =
"module Synthetic.Code\n let syntheticFunction() = \"I've been compiled on the fly!\""
// Assembly path to keep compiled code
let synthAssemblyPath = "synthetic.dll"
let CompileFSharpCode(codeString, synthAssemblyPath) =
use provider = new FSharpCodeProvider()
let options = CompilerParameters([||], synthAssemblyPath)
let result = provider.CompileAssemblyFromSource( options, [|codeString|] )
// If we missed anything, let compiler show us what's the problem
if result.Errors.Count <> 0 then
for i = 0 to result.Errors.Count - 1 do
printfn "%A" (result.Errors.Item(i).ErrorText)
result.Errors.Count = 0
if CompileFSharpCode(codeString, synthAssemblyPath) then
let synthAssembly = Reflection.Assembly.LoadFrom(synthAssemblyPath)
let synthMethod = synthAssembly.GetType("Synthetic.Code").GetMethod("syntheticFunction")
printfn "Success: %A" (synthMethod.Invoke(null, null))
else
failwith "Compilation failed"
被激发后会产生预期的输出
Success: "I've been compiled on the fly!"
如果您要使用该片段,则需要引用FSharp.Compiler.dll
and FSharp.Compiler.CodeDom.dll
. Enjoy!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)