F#将环境变量作为通用集合

Mar*_*tus 5 f# environment-variables

在.NET 4.5 Environment.GetEnvironmentVariables()中,将环境变量作为非泛型Collections.IDictionary返回.

有没有办法将F#中的环境变量作为通用集合?

Tom*_*cek 13

我不确定.NET是否有任何方法可以将环境变量作为类型化的泛型集合返回(该GetEnvironmentVariables方法自.NET 1.1以来一直存在,因此它不是通用的).如果您想自己将结果转换为通用字典,可以执行以下操作:

let envVars = 
  System.Environment.GetEnvironmentVariables()
  |> Seq.cast<System.Collections.DictionaryEntry>
  |> Seq.map (fun d -> d.Key :?> string, d.Value :?> string)
  |> dict
Run Code Online (Sandbox Code Playgroud)

这首先将结果转换为DictionaryEntry元素序列,然后提取键和值并将它们转换为字符串,然后IDictionary<string, string>使用内置dict函数进行构建.

  • `|&gt; Map.ofSeq` 也是一个选项(我不确定 OP 是否更喜欢 `Map` 但我喜欢:))。 (2认同)