如何在 C# / .Net.Core 中定义基于平台的编译时间常量 (Linux vs Windows)?

How to define compile time constants based on platform (Linux vs Windows) in C# / .Net.Core?

受到这个blog的启发,我尝试这样实现:

<DefineConstants Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Windows)))' == 'true'">Windows</DefineConstants>
<DefineConstants Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Linux)))' == 'true'">POSIX</DefineConstants>

但是我得到这个错误:

The function "IsOSPlatform" on type "System.Runtime.InteropServices.RuntimeInformation" is not available for execution as an MSBuild property function

有办法解决这个问题吗?没有那两条 DefineConstants 行,项目可以完美加载。

此方法仅适用于 15.0(或更高)版本的 MSBuild。由于此版本的 MSBuild 不附带单声道。

关于这个 here

有一个未解决的问题

Visual studio可以在.csproj文件中用这个编译代码。