使用 Windows.System 命名空间添加 CsWinRT nuget 中断

Adding CsWinRT nuget breaks using Windows.System namespace

我已经创建了一个 .NET 5.0 项目,我拥有的 dependencies 项目之一就是这个 API:

AnalyticsInfo.VersionInfo.DeviceFamily

安装 Microsoft.Windows.SDK.Contracts, I'm able to use this API. Then, I needed to install the Microsoft.Windows.CsWinRT 软件包后解决此错误:

Error   NETSDK1130  Referencing a Windows Metadata component directly when targeting 
.NETCoreApp,Version=v5.0 is not supported. 

Use the C#/WinRT projection tool (https://aka.ms/cswinrt) or a provided projection for this target.

安装后,我无法再访问 Windows.System.Profile 命名空间来调用 AnalyticsInfo API:

Error   CS0234  The type or namespace name 'System' does not exist in the namespace 'Windows' (are you missing an assembly reference?)

在 .NET 5 中,删除了 .NET 中对 WinRT API 的内置支持(因为它是 Windows 特定的),所以我们不能再使用 Microsoft.Windows.SDK.Contracts

此处Built-in support for WinRT is removed from .NET解释的解决方案是

Remove references to the Microsoft.Windows.SDK.Contracts package. Instead, specify the version of the Windows APIs that you want to access via the TargetFramework property of the project. For example:

<TargetFramework>net5.0-windows10.0.19041</TargetFramework>

请注意,有了它,就无需手动添加对 C#/WinRT 的引用 (Microsoft.Windows.CsWinRT),它应该会自动完成并在框架列表中显示为“Microsoft.Windows.SDK.NET.Ref”依赖项。