有没有办法在 F# 中通过字符串获取记录字段?

Ist*_*van 3 f#

我想通过用字符串查找来获取记录中字段的值。

type Test = { example : string  }
let test = { example = "this is the value" }
let getByName (s:string) =
  ???? //something like test.GetByName(s)
Run Code Online (Sandbox Code Playgroud)

361*_*615 5

对于这种情况,标准.net 反射应该可以正常工作。记录字段作为属性公开,因此您可以使用反射 API 查询类型。它可能看起来像这样:

  let getByName (s:string) =
    match typeof<Test>.GetProperties() |> Array.tryFind (fun t -> t.Name = s)
      with
      | Some pi -> Some(pi.GetValue(test))
      | None -> None
Run Code Online (Sandbox Code Playgroud)

  • 只是使用库函数进行了一个小优化:``let getByName s = typeof&lt;Test&gt;.GetProperties () |&gt; Array.tryFind (fun t -&gt; t.Name = s) |&gt; Option.map (fun pi -&gt; pi .GetValue测试)`` (3认同)