2017-03-14 34 views
1

我正在構建一個小項目來更好地理解F#。作爲它的一部分,我想要一個使用System.Configuration.ConfigurationManager的函數「myAppSettings」來讀取AppSettings.config文件中的設置。我把這個在我的解決方案稱爲myAppSettings一個單獨的文件,它看起來像這樣:F#試圖訪問ConfigurationManager

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 

然而,這並不編譯,我得到的錯誤:

Error 1 The namespace or module 'ConfigurationManager' is not defined

我知道,這個對象是在System.Configuration(從C#開始一直使用它),所以我必須在某處有語法錯誤,但是在哪裏?

我也試過:

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

然後發現ConfigurationManager中(新的關鍵字幫助),但是反對「讓價值」:

Error 1 Incomplete structured construct at or before this point in expression

我想了解兩個錯誤消息以及訪問app.config文件中設置的正確方法。

+0

這個問題是不是'ConfigurationManager'在當前上下文中不可用,它是關於從F#訪問'ConfigurationManager'的。 –

回答

2

你的問題是你如何訪問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) 
+0

工作!雖然我必須添加一個類型註釋到「key」,因爲它可以是一個字符串或一個整數。合理? – user1443098

+0

@ user1443098是的,這確實有意義 –