c# - os的Visual Studio条件编译

标签 c# asp.net .net cross-platform .net-standard-2.0

我知道有一种方法可以为目标框架有条件地编译,例如#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/

相关文章:

c# - Uri.EscapeDataString 怪异

c# - 字符串中的 Unicode 字符

c# - MVC3 动态 ListView

c# - 如何获取 linq `ForEach` 语句以返回有关为每个列表对象进行的方法调用的数据?

c# - SignalR OnConnected - 向连接的客户端发送消息

c# - 使用属性名称作为字符串进行排序

c# - VSTO:为什么 OfficeRibbon.Context 为空?

c# - 标准 POST 请求的结构是什么

c# - 通过 boundfield 将 DBCONTEXT 绑定(bind)到 gridview

c# - 获取所有字母字符的数组