我知道有一种方法可以为目标框架有条件地编译,例如#if net461 ....#elif ....
但是有没有办法为特定的操作系统有条件地编译
像 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
关于c# - os的Visual Studio条件编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49911281/