dot net core build platform/os特定代码或类文件

Dam*_*ien 5 .net macos .net-core visual-studio-code

我想构建一个.net核心库,它将具有用于执行win32和osx调用的特定于平台的代码,并且在为每个目标操作系统编译库时,我想要包含正确的os代码.

我查看了corefx和许多文档,经过大量的google搜索,我发现的唯一方法是在运行时执行操作系统检测,但这既低效又乏味.在corefx的情况下,他们有一个复杂的构建系统,似乎自动提取特定于平台的文件,但依赖于msbuild等.我错过了什么吗?

如何在文件级别或代码级别有条件地定位操作系统的代码,例如:

#if osx
// come code
#endif
Run Code Online (Sandbox Code Playgroud)

或者,按照golang方式,通过将os名称放在文件名中,例如MyClass.osx.cs用于osx代码,将MyClass.cs用于非平台内容,构建过程将包含正确的文件本身.

我正在使用Visual Studio代码和project.json.

(我想在Visual Studio中我可以定义每个平台目标并包含我自己的定义,但我在osx上)

提前致谢.

cwi*_*hva 4

您可以在 project.json 中定义构建定义

"buildOptions": {
                "define": [ "PORTABLE328" ]
            }
Run Code Online (Sandbox Code Playgroud)

例如:

{
    "frameworks":{
        "netstandard1.6":{
           "dependencies":{
                "NETStandard.Library":"1.6.0",
            }
        },
        ".NETPortable,Version=v4.0,Profile=Profile328":{
            "buildOptions": {
                "define": [ "PORTABLE328" ]
            },
            "frameworkAssemblies":{
                "mscorlib":"",
                "System":"",
                "System.Core":"",
                "System.Net"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您可以针对该目标有条件地进行编译:

#if !PORTABLE328
using System.Net.Http;
using System.Threading.Tasks;
// Potentially other namespaces which aren't compatible with Profile 328
#endif
Run Code Online (Sandbox Code Playgroud)

来源