繁体   English   中英

os的Visual Studio条件编译

[英]Visual studio conditional compilation for os

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

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

第 2 部分:另外,有没有办法创建自定义标签,这样每当新目标操作系统或框架发生更改时,我就不必更改每个标签。例如,从 net461 到 net471

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

您不需要有不同的配置并手动选择要使用的配置。

您可以使用 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/ 链接中的最少信息:更改您的 .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

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

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

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

配置管理器

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

创建新配置

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

条件编译符号

对 Windows 执行相同操作。

然后您可以编写如下条件步骤:

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

        Console.Read();
    }

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

操作系统:

操作系统

窗户:

窗户

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM