CA1416。如何告诉构建器只有平台是Windows?

CA1416. How to tell builder that only platform is Windows?

dotnet run(在 windows 上)原因 warning CA1416: This call site is reachable on all platforms. 'WellKnownSidType.WorldSid' is only supported on: 'windows'.

我的程序设计为 运行 仅适用于 windows。

我尝试将 SupportedPlatform 添加到 MyApp.csproj,但没有成功。

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.Negotiate" Version="5.0.5" />
    <PackageReference Include="System.DirectoryServices" Version="5.0.0" />
    <SupportedPlatform Include="Windows"/>
  </ItemGroup>

</Project>

我做错了什么?我如何显示 dotnet run 这个项目是 windows-only?

您可以用 System.Runtime.Versioning.SupportedOSPlatformAttribute 标记每个 windows 特定方法,例如

[SupportedOSPlatform("windows")]
public static void Foo()
    => Thread.CurrentThread.SetApartmentState(ApartmentState.STA);

在 AssemblyInfo 中标记整个程序集(如果有的话)

[assembly: System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]

或编辑 .csproj 文件以针对 windows-特定版本的 dotnet 以使这些更改自动进行

<TargetFramework>net5.0-windows</TargetFramework>