我想通过用字符串查找来获取记录中字段的值。
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)
对于这种情况,标准.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)