我想通过用字符串查找来获取记录中字段的值。
type Test = { example : string }
let test = { example = "this is the value" }
let getByName (s:string) =
???? //something like test.GetByName(s)
标准.net 反射 https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection对于这种情况应该可以正常工作。记录字段作为属性公开,因此您只需使用反射 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)