[英]F# Get Members of Module
Given 给定
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 }
How can I create a function with this signature? 如何使用此签名创建函数?
let units () : Units[] = ...
F# Modules are just static classes when compiled. F#模块在编译时只是静态类。
Using reflection you should be able to grab these values with something like this: 使用反射,您应该可以通过以下方式获取这些值:
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)
It's tricky to get the type of the module, but that trick will do it for you. 获取模块的类型很棘手,但是这种技巧将为您做到这一点。
EDIT: 编辑:
Updated to cast directly to Unit
. 更新以直接投射到Unit
。 The cast as shown is unsafe, and will throw if GetValue
does not return a Unit
type. 所示的转换是不安全的,如果GetValue
不返回Unit
类型,则将抛出该转换。
Additionally unit
is a type in F#, it might be clearer to use a different name. 另外, unit
是F#中的一种类型,使用其他名称可能会更清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.