What is the proper way to handle error CA1416 for .NET core builds?

房东的猫 提交于 2021-02-20 10:16:36

问题


Here is my C# code snippet:

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

When I run the build, I get an error:

error CA1416: 'GetSessionBusAddressFromSharedMemory()' is supported on 'windows' 

My logic is to invoke the method only when I am on Windows. How do I turn this warning off when building on Ubuntu? Regards.


回答1:


You can use a preprocessor directive to make sure that the method gets seen at compile time only in Windows:

#if Windows
private static string GetSessionBusAddressFromSharedMemory() 
{
   ...
}
#endif

To define the directives you need to update your csproj as follows:

<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>


来源:https://stackoverflow.com/questions/65165941/what-is-the-proper-way-to-handle-error-ca1416-for-net-core-builds

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!