繁体   English   中英

F#获取模块成员

[英]F# Get Members of Module

给定

type Unit = {
            Name : string
            Abbreviation : string
            Value : float
        }

module Lets =
    let meter = { Name = "meter"; Abbreviation = "m"; Value = 1.0 }
    let millimeter = { Name = "millimeter"; Abbreviation = "mm"; Value = 1e-3 }

如何使用此签名创建函数?

let units () : Units[] = ...

F#模块在编译时只是静态类。

使用反射,您应该可以通过以下方式获取这些值:

module Lets =
    type Dummy = | Dummy
    let meter = { Name = "meter"; Abbreviation = "m"; Value = 1.0 }
    let millimeter = { Name = "millimeter"; Abbreviation = "mm"; Value = 1e-3 }


let t = typeof<Lets.Dummy>.DeclaringType
t.GetProperties() |> Array.map(fun p -> p.GetValue(null, null) :?> Unit)

获取模块的类型很棘手,但是这种技巧将为您做到这一点。

编辑:

更新以直接投射到Unit 所示的转换是不安全的,如果GetValue不返回Unit类型,则将抛出该转换。

另外, unit是F#中的一种类型,使用其他名称可能会更清楚。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM