首页 > 解决方案 > 我可以在运行时解析一些引用当前程序集中类型的 F# 代码吗?

问题描述

假设我定义了以下类型:

type Foo = { A: string; B: int }

我想要一个函数parse,这样:

let myfoo = parse<Foo> "{A = \"foo\"; B = 5}"

给我一个 Foo 类型的实例(或错误)。

这可以使用 FSharp.Compiler.Service 吗?

更新:

虽然还有其他问题涉及 F# 代码的解析,但它们没有解决在当前程序集中具有引用的问题。

标签: f#f#-compiler-services

解决方案


您可以通过从托管的 F# 交互中引用当前程序集来执行此操作 - 只有当您从已编译的程序(其程序集位于磁盘上)运行它并且您的类型是公共的时,这才有效,但它可能会在您的案子。

鉴于Embedding F# Interactive page 上记录的常用设置,您可以执行以下操作:

module Program

type Test = { A:int; B:string }

// (omitted code to initialize the fsi service)
let fsiSession = FsiEvaluationSession.Create(...)    

// Run #r command to reference the current assembly  
let loc = System.Reflection.Assembly.GetExecutingAssembly().Location
fsiSession.EvalInteraction(sprintf "#r @\"%s\"" loc)

// Open the module or namespace containing your types
fsiSession.EvalInteraction("open Program")

// Evaluate code using the type and cast it back to our type
let value = fsiSession.EvalExpression("{A=0; B=\"hi\"}").Value.ReflectionValue :?> Test
printfn "%A" value

推荐阅读