简体   繁体   English

如何在F#中获取模块的类型

[英]How to get type of the module in F#

How to get 'System.Type' of the module? 如何获得模块的'System.Type'?

For example module: 例如模块:

module Foo =
     let bar = 1

And this does not work: 这不起作用:

printfn "%s" typeof<Foo>.Name

Error is: 错误是:

The type 'Foo' is not defined

You could add a marker type to the module and then discover the module's type from that: 您可以向模块添加标记类型,然后从中发现模块的类型:

module Foo =  
    type internal Marker = interface end
    let t = typeof<Marker>.DeclaringType

It would certainly be nice to have a moduleof operator... Since there's not one, the easiest way to do what you want is probably to use the Metadata library in the F# PowerPack: 这肯定是有一个好的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

Unfortunately, this won't work with dynamic assemblies (such as those generated via F# Interactive). 不幸的是,这不适用于动态程序集(例如通过F#Interactive生成的程序集)。 You can do something similar using vanilla System.Reflection calls, but that's more dependent on having a good understanding of the compiled form that your module takes. 您可以使用vanilla System.Reflection调用执行类似的操作,但这更依赖于对模块所采用的编译表单的充分理解。

It can also be done using Quotations . 它也可以使用报价来完成。 First, define this helper function somewhere: 首先,在某处定义这个辅助函数:

open Microsoft.FSharp.Quotations.Patterns

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

Then, you can define a module and get its type like this: 然后,您可以定义一个模块并获取其类型:

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

Hope this helps. 希望这可以帮助。

module name is not a type. 模块名称不是类型。

List in List.map and let (a:List<int>) = [1;2;3] are different. List.map Listlet (a:List<int>) = [1;2;3]是不同的。

The first List is a module name, the second is a type. 第一个List是模块名称,第二个是类型。

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

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