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 不是 return 一个 Unit 类型就会抛出。

此外 unit 是 F# 中的一种类型,使用不同的名称可能更清楚。