f# - 我可以在运行时解析一些引用当前程序集中类型的 F# 代码吗?
问题描述
假设我定义了以下类型:
type Foo = { A: string; B: int }
我想要一个函数parse
,这样:
let myfoo = parse<Foo> "{A = \"foo\"; B = 5}"
给我一个 Foo 类型的实例(或错误)。
这可以使用 FSharp.Compiler.Service 吗?
更新:
虽然还有其他问题涉及 F# 代码的解析,但它们没有解决在当前程序集中具有引用的问题。
解决方案
您可以通过从托管的 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
推荐阅读
- r - 如何在 R Markdown 中将日期和时间拆分为两个单独的列
- azure - 如何确保 Azure 函数调用中的用户身份?ASP NET Core Web 应用程序
- sql-server - 使用实体框架更新后,日期时间默认值为空
- r - 如何计算 R 中两个掷骰子之和的矩阵?
- javascript - TypeScript 可选对象键未按预期运行
- scala - 重命名类而不重命名伴随对象?
- scala - 如何在具有多个子项目的 SBT 项目中覆盖子项目中的设置
- azure-functions - Azure 计时器功能:本地设置“RunOnStartup 为 true”无法按预期工作
- json - 从嵌套的 JSON 字符串中检索元素
- python - 如何强制图形轴为整数?