代码之家  ›  专栏  ›  技术社区  ›  Mike Chaliy

如何在f中获取模块类型#

  •  19
  • Mike Chaliy  · 技术社区  · 15 年前

    如何获取模块的“system.type”?

    例如模块:

    module Foo =
         let bar = 1
    

    但这不起作用:

    printfn "%s" typeof<Foo>.Name
    

    错误是:

    The type 'Foo' is not defined
    
    4 回复  |  直到 15 年前
        1
  •  7
  •   kvb    15 年前

    如果有一个 moduleof 操作员…因为没有一种方法,所以最简单的方法可能是使用f_powerpack中的元数据库:

    #r "FSharp.PowerPack.Metadata.dll" 
    open Microsoft.FSharp.Metadata
    
    // get .NET assembly by filename or other means
    let asm = ...
    
    let fasm = FSharpAssembly.FromAssembly asm
    let t = fasm.GetEntity("Foo").ReflectionType
    

    不幸的是,这不适用于动态程序集(例如通过f_interactive生成的程序集)。你可以用香草做类似的事情 System.Reflection 调用,但这更依赖于对模块所采用的编译形式有一个良好的理解。

        2
  •  28
  •   Phillip Trelford    12 年前

    您可以向模块添加标记类型,然后从中发现模块的类型:

    module Foo =  
        type internal Marker = interface end
        let t = typeof<Marker>.DeclaringType
    
        3
  •  5
  •   Nikon the Third    10 年前

    也可以使用 Quotations 。首先,在某个地方定义这个助手函数:

    open Microsoft.FSharp.Quotations.Patterns
    
    let getModuleType = function
    | PropertyGet (_, propertyInfo, _) -> propertyInfo.DeclaringType
    | _ -> failwith "Expression is no property."
    

    然后,您可以定义一个模块并得到它的类型,如下所示:

    module SomeName =
        let rec private moduleType = getModuleType <@ moduleType @>
    

    希望这有帮助。

        4
  •  -1
  •   Yin Zhu    15 年前

    模块名不是类型。

    List 在里面 List.map let (a:List<int>) = [1;2;3] 是不同的。

    第一个 是模块名,第二个是类型。