处理 .NET 核心构建的错误 CA1416 的正确方法是什么?

Pet*_*ter 5 c# .net-core

这是我的 C# 代码片段:

if (Environment.IsWindows) {
   _sessionAddress = GetSessionBusAddressFromSharedMemory();
}
...
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
private static string GetSessionBusAddressFromSharedMemory() {
   ...
}
Run Code Online (Sandbox Code Playgroud)

当我运行构建时,我收到一个错误:

error CA1416: 'GetSessionBusAddressFromSharedMemory()' is supported on 'windows' 
Run Code Online (Sandbox Code Playgroud)

我的逻辑是仅当我在 Windows 上时才调用该方法。在 Ubuntu 上构建时如何关闭此警告?问候。

bre*_*dev 4

您可以使用预处理器指令来确保该方法仅在 Windows 中在编译时可见:

#if Windows
private static string GetSessionBusAddressFromSharedMemory() 
{
   ...
}
#endif
Run Code Online (Sandbox Code Playgroud)

要定义指令,您需要更新 csproj,如下所示:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <IsWindows Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Windows)))' == 'true'">true</IsWindows>
    <IsOSX Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::OSX)))' == 'true'">true</IsOSX>
    <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="'$(IsOSX)'=='true'">
    <DefineConstants>OSX</DefineConstants>
  </PropertyGroup>
  <PropertyGroup Condition="'$(IsLinux)'=='true'">
    <DefineConstants>Linux</DefineConstants>
  </PropertyGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)