简体   繁体   中英

How to get type of the module in F#

How to get 'System.Type' of the module?

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:

#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). 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.

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.

The first List is a module name, the second is a type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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