-->

定义模块VS.NET VS F#互动(Defining Modules VS.NET vs F# I

2019-09-21 18:42发布

我写了这个代码编译并在2010年VS.NET工程完美

module ConfigHandler
open System
open System.Xml
open System.Configuration

let GetConnectionString (key : string) =
  ConfigurationManager.ConnectionStrings.Item(key).ConnectionString

然而,当我做了控制+ A和Alt + Enter键发送这FSI我得到一个错误

ConfigHandler.fs(2,1):错误FS0010:在定义构造结构的意外启动。 预期“=”或其它令牌。

好。

所以,我改变我的代码

module ConfigHandler =
  open System
  open System.Xml
  open System.Configuration

  let GetConnectionString (key : string) =
    ConfigurationManager.ConnectionStrings.Item(key).ConnectionString

现在控制+ A,Alt + Enter键是成功的,我FSI很好地告诉我

模块ConfigHandler =开始VAL GetConnectionString:串 - >串端

但是现在,如果我尝试编译我的代码在VS.NET 2010,我得到一个错误信息

在图书馆或多个文件应用程序文件必须与命名空间或模块的声明,如“命名空间SomeNamespace.SubNamespace”或“模块SomeNamespace.SomeModule”开始

我怎样才能兼得? 能力VS.NET和发送模块FSI的能力编译程序吗?

Answer 1:

有一个微小的 - 但至关重要的 - 你的代码的两个片段之间的差异是在这里指责。

F#有两种方式来声明一个module 。 首先,一个“顶层模块”,声明如下:

module MyModule
// ... code goes here

另一种方式来声明一个模块是作为一个“本地模块”,就像这样:

module MyModule =
    // ... code goes here

的“顶级”和“本地”声明之间的主要区别是,局部声明之后是=符号和一个“本地”模块中的代码必须缩进。

究其原因,你得到ConfigHandler.fs(2,1): error FS0010: Unexpected start of structured construct in definition. Expected '=' or other token. ConfigHandler.fs(2,1): error FS0010: Unexpected start of structured construct in definition. Expected '=' or other token. 第一个片段的信息是,你不能在声明顶层模块fsi

当您添加=登录到你的模块定义,它从一个顶层模块改为本地模块。 从那里,你得到了错误Files in libraries or multiple-file applications must begin with a namespace or module declaration, eg 'namespace SomeNamespace.SubNamespace' or 'module SomeNamespace.SomeModule' ,因为局部模块必须嵌套在顶层模块中或命名空间。 fsi不允许你定义命名空间(或顶层模块),所以如果你想将整个文件复制粘贴到fsi只有它会工作的方式是,如果你使用的编译指令作为@pad提及。 否则,你可以简单地复制粘贴本地模块定义(不包含命名空间)为fsi和预期,他们应该工作。

参考: 模块(F#)MSDN上



Answer 2:

常见的解决办法是保持第一示例,并创建一个fsx它引用模块文件:

#load "ConfigHandler.fs"

你有优势,加载多个模块和编写相关的代码进行实验。

如果你真的想加载ConfigHandler.fs直接把F#互动,您可以使用INTERACTIVE符号和编译器指令 :

#if INTERACTIVE
#else
module ConfigHandler
#endif

它同时适用于FSI和FSC。



文章来源: Defining Modules VS.NET vs F# Interactive