简体   繁体   中英

Can I parse some F# code at run-time that reference types in my current assembly?

Say I have the following type defined:

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

I want a function parse , such that:

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

gives me an instance of type Foo (or error).

Is this possible using FSharp.Compiler.Service?

UPDATE:

While there are other questions that address parsing of F# code, they don't address having references in the current assembly.

You can do this by referencing the current assembly from the hosted F# interactive - this only works if you are running this from a compiled program (which has assembly located on disk) and if your types are public, but it may do the trick in your case.

Given the usual setup documented on the Embedding F# Interactive page , you can do something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM