1

我们是多人在同一个 F# 项目上工作。一些将 MacOS 和 Visual Studio Code 与Ionide一起使用,而另一些则将 Windows 与 Visual Studio 一起使用。在 F# 代码中,我们需要访问一些文件,但 MacOS 使用/指定路径,而 Windows 使用\. 在 F# 中,我们如何进行如下操作:

#if OS_WINDOWS
    let path = "path\to\file.txt"
#elif OS_MAC
    let path = "path/to/file.txt"
#endif
4

1 回答 1

3

There is no built-in pre-defined symbol to indicate what operating system you are compiling for. When you use .NET, you generally use the same compiled assembly on all operating systems, so this is not something that you can reasonably do in a pre-processor anyway.

You can check what OS are you running on at runtime using System.Environment:

open System

let path = 
  if Environment.OSVersion.Platform = PlatformID.Win32NT then @"path\to\file.txt"
  else @"path/to/file.txt"

That said, if your only concern is slashes and backslashes in a path, you can just use:

let path = System.IO.Path.Combine("path", "to", "file.txt")
于 2020-01-09T14:34:20.617 回答