【问题标题】:Auto open a namespace in F#在 F# 中自动打开命名空间
【发布时间】:2012-03-21 18:16:11
【问题描述】:

您好想知道如何让 f# 编译器自动打开命名空间。

我有

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 = 
    ....

谢谢

【问题讨论】:

  • 为什么需要这样做?自动打开模块对你来说还不够吗?
  • 不,我希望一旦我从外部项目中引用了库,XXX.YYY 的路径就会自动打开,我可以访问模块 XXX.YYY 中的函数我知道它正在寻找就像我的代码 sn-p 中的一样,但我不记得了

标签: f# module namespaces


【解决方案1】:

为了打开命名空间/模块而不先打开其父级,您必须在程序集级别添加属性。 您可以通过将 AssemblyInfo.fs 文件添加到您的项目来做到这一点:

在以下代码的情况下:

namespace Framework

module GlobalFunctions = 

  let Test () =
    10.

例如,您可以将以下代码添加到 AssemblyInfo.fs:

namespace Framework

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

do()

然后您可以从脚本 (.fsx) 文件中调用代码:

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

let result = Test ()

导致:

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

【讨论】:

    【解决方案2】:

    AutoOpen 属性只能应用于 F# module,因此您无法将其添加到整个 namespace。但是,由于您可以将所有 F# 声明放在一个模块中,这可能足以满足您的需要。语法是:

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

    当您引用程序集时,您应该会立即看到Foo。如果声明放在另一个命名空间(即MyLibrary)中,则需要添加open MyLibrary,但MyGlobals 将自动访问。

    【讨论】:

    • 嗨 Tomas,请参阅我之前对 pad 的评论。我想要的与您的建议略有不同
    猜你喜欢
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 2013-11-10
    • 2019-10-21
    • 2010-11-12
    • 2019-10-10
    • 2010-09-16
    • 2011-01-22
    相关资源
    最近更新 更多