我可以在 运行 时间解析一些引用当前程序集中类型的 F# 代码吗?
Can I parse some F# code at run-time that reference types in my current assembly?
假设我定义了以下类型:
type Foo = { A: string; B: int }
我想要一个函数 parse
,这样:
let myfoo = parse<Foo> "{A = \"foo\"; B = 5}"
给我一个 Foo 类型的实例(或错误)。
这可以使用 FSharp.Compiler.Service 吗?
更新:
虽然还有其他问题可以解决 F# 代码的解析问题,但它们没有解决当前程序集中的引用问题。
您可以通过从托管的 F# 交互中引用当前程序集来执行此操作 - 这仅在您是 运行 来自已编译程序(其程序集位于磁盘上)并且您的类型是 public,但它可能对您的情况有用。
给定 usual setup documented on the 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
假设我定义了以下类型:
type Foo = { A: string; B: int }
我想要一个函数 parse
,这样:
let myfoo = parse<Foo> "{A = \"foo\"; B = 5}"
给我一个 Foo 类型的实例(或错误)。
这可以使用 FSharp.Compiler.Service 吗?
更新:
虽然还有其他问题可以解决 F# 代码的解析问题,但它们没有解决当前程序集中的引用问题。
您可以通过从托管的 F# 交互中引用当前程序集来执行此操作 - 这仅在您是 运行 来自已编译程序(其程序集位于磁盘上)并且您的类型是 public,但它可能对您的情况有用。
给定 usual setup documented on the 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