F#尝试访问ConfigurationManager

3

我正在构建一个小项目来更好地理解F#。 作为其中的一部分,我想要一个名为“myAppSettings”的函数,它使用System.Configuration.ConfigurationManager从AppSettings.config文件中读取设置。 我将其放在解决方案中的一个单独文件中,名为myAppSettings,它看起来像这样:

namespace foo.bar
open System
open System.Configuration

module myAppSettings =
    let read key mandatory = 
        let appSettings = ConfigurationManager.AppSettings
        let value = appSettings key
        if mandatory && String.IsNullOrEmpty(value) then
            failwith "bad hombres"
        value

然而,这段代码无法编译,我收到了以下错误信息:

错误1:未定义名称空间或模块“ConfigurationManager”

我知道该对象在System.Configuration中(我经常从C#中使用它),所以我一定是哪里语法出错了,但是具体在哪里呢?

我还尝试过:

let appSettings = new ConfigurationManager.AppSettings
let value = appSettings key

然后找到了ConfigurationManager(使用了new关键字),但是对"let value"提出了反对:

Error 1 在表达式中此点或之前的结构不完整

我想了解这两个错误消息以及正确访问app.config文件中设置的方法。


这个问题不是关于ConfigurationManager在当前上下文中不可用,而是关于如何从F#访问ConfigurationManager - Sven Grosen
1个回答

4

您的问题在于您如何访问ConfigurationManager

namespace foo.bar
open System
open System.Configuration

module myAppSettings =
    let read key mandatory = 
        //let appSettings = ConfigurationManager.AppSettings
        //let value = appSettings key
        let value = ConfigurationManager.AppSettings.Item(key)
        if mandatory && String.IsNullOrEmpty(value) then
            failwith "bad hombres"
        value

如果你想保持双重访问,请尝试以下方法:

let appSettings = ConfigurationManager.AppSettings
let value = appSettings.Item(key)

成功了!虽然我不得不给“key”添加一个类型注释,因为它可以是字符串或整数。明白吗? - user1443098
@user1443098 是的,那确实有道理。 - Sven Grosen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接