Visual studio os 的条件编译

Visual studio conditional compilation for os

我知道有一种方法可以针对目标框架进行条件编译,例如#if net461 ....#elif .... 但是有没有办法有条件地编译特定的 os 喜欢目标 _os_MAC 或 target_os_win

如果有人可以指导我如何实现它的文档或教程?

第 2 部分: 另外,有没有一种方法可以创建自定义标签,这样我就不必在新目标 os 或框架发生变化时更改每个标签。例如,从 net461 到 net471

此答案假设您询问的是自定义预处理器符号(这就是我的解释方式 - 如果我错了请纠正我。

您可以使用自定义构建配置:

首先进入构建配置管理器..

接下来,创建一个新的构建配置。您可以从现有配置复制配置:

然后,右键单击您的项目并转到属性。在构建选项卡下,定义一个条件编译符号:

对 Windows 执行相同的操作。

然后你可以像下面这样写条件步骤:

    class Program
{
    static void Main(string[] args)
    {
#if MACOS
        Console.WriteLine("OSX");
#elif WINDOWS
        Console.WriteLine("Windows");
#endif

        Console.Read();
    }

根据您选择的构建配置..您将获得:

OSX:

Windows:

这是一个老问题,但如果现在有人来这里,会有更好的选择。

您不需要有不同的配置和select 手动使用哪个配置。

您可以使用 System.Runtime.InteropServices.RuntimeInformation。 https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.runtimeinformation?view=netframework-4.8

这里有一本很好的手册:https://blog.magnusmontin.net/2018/11/05/platform-conditional-compilation-in-net-core/ 来自 link 的最少信息: 更改您的 .csproj 文件

<PropertyGroup> 
 <OutputType>Exe</OutputType> 
 <TargetFramework>netcoreapp2.0</TargetFramework> 
 <IsWindows Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Windows)))' == 'true'">true</IsWindows> 
 <IsLinux Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Linux)))' == 'true'">true</IsLinux> 
</PropertyGroup>
<PropertyGroup Condition="'$(IsWindows)'=='true'">
 <DefineConstants>Windows</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(IsLinux)'=='true'">
 <DefineConstants>Linux</DefineConstants>
</PropertyGroup>

这将有条件地定义常量。您以后可以这样使用:

#if Linux
    Console.WriteLine("Built on Linux!"); 
#elif Windows
    Console.WriteLine("Built in Windows!"); 
#endif