有没有办法在F#中按字符串获取Record字段? [英] Is there a way to get Record fields by string in F#?

查看:38
本文介绍了有没有办法在F#中按字符串获取Record字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过用字符串查找字段来获取Record中字段的值.

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)

推荐答案

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

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

这篇关于有没有办法在F#中按字符串获取Record字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆