如何将文本字符串(应该是 F# 代码)解析为 F# 代码,以在屏幕上打印结果?
我猜它会通过 .NET 中的一个特性来解决,所以它可以通过 F# 本身或 C# 来完成。
这在tryfsharp.org上可能以何种方式解决?
最佳答案
可以使用 F# CodeDom provider 实现所需的功能.下面的最小可运行代码段演示了所需的步骤。它从字符串中获取任意可能正确的 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
和 FSharp.Compiler.CodeDom.dll
.享受!
关于.net - 将文本字符串解析为 F# 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9945382/