简体   繁体   中英

Auto open a namespace in F#

Hi would like to know how to make the f# compiler to auto open a namespace automatically.

I have

namespace XXX 

I have to add something here do(AutoOpen("XXX.YYY")) or something like that to make the XXX.YYY module to be opened when referencing the library from external projects.

[<AutoOpen>]
module YYY = 
    ....

Thanks

In order to open a namespace/module without opening its parent first, you have to add the attribute on assembly level. You can do this by adding an AssemblyInfo.fs file to your project:

In the case of the following code:

namespace Framework

module GlobalFunctions = 

  let Test () =
    10.

You would for instance add the following code to AssemblyInfo.fs:

namespace Framework

[<assembly:AutoOpen("Framework.GlobalFunctions")>]

do()

And then you can call the code from a script (.fsx) file with:

#r @"C:\PathToAssembly\Assembly.dll"

let result = Test ()

Resulting in:

--> Referenced 'C:\PathToAssembly\Assembly.dll'
val result : float = 10.0

The AutoOpen attribute can be applied only to F# module , so you won't be able to add it to an entire namespace . However, since you can place all F# declarations inside a module, that may be enough for what you need. The syntax is:

[<AutoOpen>]
module MyGlobals =
  // Declarations in the module
  type Foo() = 
    member x.Bar = 10

When you reference the assembly, you should see Foo immediately. If the declaration is placed inside another namespace (ie MyLibrary ), then you'll need to add open MyLibrary , but MyGlobals will be accessible automatically.

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