Reputation: 8562
I would like to get the value of a field in a Record by looking it up with a string.
type Test = { example : string }
let test = { example = "this is the value" }
let getByName (s:string) =
???? //something like test.GetByName(s)
Upvotes: 4
Views: 1650
Reputation: 3877
Standard .net reflection should be working fine for such scenario. Record fields are exposed as properties, so you can just query the type with reflection API. It could look like this:
let getByName (s:string) =
match typeof<Test>.GetProperties() |> Array.tryFind (fun t -> t.Name = s)
with
| Some pi -> Some(pi.GetValue(test))
| None -> None
Upvotes: 7