[英]Auto open a namespace in F#
Hi would like to know how to make the f# compiler to auto open a namespace automatically. 您想知道如何使f#编译器自动打开命名空间。
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: 您可以通过向项目添加AssemblyInfo.fs文件来执行此操作:
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: 例如,您可以将以下代码添加到AssemblyInfo.fs:
namespace Framework
[<assembly:AutoOpen("Framework.GlobalFunctions")>]
do()
And then you can call the code from a script (.fsx) file with: 然后,您可以使用以下命令从脚本(.fsx)文件调用代码:
#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
. AutoOpen
属性只能应用于F# module
,因此您无法将其添加到整个namespace
。 However, since you can place all F# declarations inside a module, that may be enough for what you need. 但是,由于您可以将所有F#声明放在模块中,这可能足以满足您的需要。 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. 引用程序集时,应立即看到Foo
。 If the declaration is placed inside another namespace (ie MyLibrary
), then you'll need to add open MyLibrary
, but MyGlobals
will be accessible automatically. 如果声明放在另一个名称空间(即MyLibrary
)中,那么您需要添加open MyLibrary
,但MyGlobals
将自动访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.