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