【问题标题】:F# Get Members of ModuleF# 获取模块的成员
【发布时间】:2019-04-12 23:03:09
【问题描述】:

给定

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[] = ...

【问题讨论】:

    标签: reflection module f# member


    【解决方案1】:

    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# 中的一种类型,使用不同的名称可能更清楚。

    【讨论】:

    • 非常好。我编辑了答案以包含 Unit 类型的定义,并且我想返回 Units[] 而不是 obj[]
    • 在这种情况下,您必须强制转换为Units,我会相应地更新我的答案
    猜你喜欢
    • 1970-01-01
    • 2015-06-01
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 2013-06-01
    相关资源
    最近更新 更多