验证兼容的框架

包含兼容框架的包需要确保针对一个框架编译的代码可以针对另一个运行。 兼容框架对的示例包括:

  • .NET Standard 2.0 和 .NET 7
  • .NET 6 和 .NET 7

在这两种情况下,使用者都可以基于 .NET Standard 2.0 或 .NET 6 进行生成,并在 .NET 7 上运行。 如果二进制文件在这些框架之间不兼容,使用者最终可能会出现编译时或运行时错误。

包验证在打包过程中捕捉这些错误。 下面是一个示例方案:

假设你正在编写一个处理字符串的游戏。 需要同时支持 .NET Framework 和 .NET (.NET Core) 使用者。 最初,你的项目面向 .NET Standard 2.0,但现在你想要利用 Span<T> .NET 6 来避免不必要的字符串分配。 为此,需要同时以 .NET Standard 2.0 和 .NET 6 为目标。

你已编写以下代码:

#if NET6_0_OR_GREATER
    public void DoStringManipulation(ReadOnlySpan<char> input)
    {
        // use spans to do string operations.
    }
#else
    public void DoStringManipulation(string input)
    {
        // Do some string operations.
    }
#endif

然后,尝试打包项目(使用 dotnet pack 或 Visual Studio),结果出现以下错误而导致失败:

D:\demo>dotnet pack
Microsoft (R) Build Engine version 17.0.0-preview-21460-01+8f208e609 for .NET
Copyright (C) Microsoft Corporation. All rights reserved.

  Determining projects to restore...
  All projects are up-to-date for restore.
  You are using a preview version of .NET. See: https://aka.ms/dotnet-core-preview
  You are using a preview version of .NET. See: https://aka.ms/dotnet-core-preview
  PackageValidationThrough -> D:\demo\bin\Debug\netstandard2.0\PackageValidationThrough.dll
  PackageValidationThrough -> D:\demo\bin\Debug\net6.0\PackageValidationThrough.dll
  Successfully created package 'D:\demo\bin\Debug\PackageValidationThrough.1.0.0.nupkg'.
C:\Program Files\dotnet\sdk\6.0.100-rc.1.21463.6\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Compatibility.Common.targets(32,5): error CP0002: Member 'A.B.DoStringManipulation(string)' exists on lib/netstandard2.0/PackageValidationThrough.dll but not on lib/net6.0/PackageValidationThrough.dll [D:\demo\PackageValidationThrough.csproj]

CompatibleFrameworks

你意识到,与其为 .NET 6 排除 DoStringManipulation(string),不如为 .NET 6 提供一个额外的 DoStringManipulation(ReadOnlySpan<char>) 方法:

#if NET6_0_OR_GREATER
    public void DoStringManipulation(ReadOnlySpan<char> input)
    {
        // use spans to do string operations.
    }
#endif
    public void DoStringManipulation(string input)
    {
        // Do some string operations.
    }

你再次尝试打包项目,结果成功。

兼容框架成功

严格模式

可以通过在项目文件中设置EnableStrictModeForCompatibleFrameworksInPackage来为此验证程序启用严格模式。 启用严格模式会更改某些规则,并在获取差异时执行其他一些规则。 如果希望所比较的双方在领域和标识方面完全相同,这十分有用。 有关详细信息,请参阅 “严格”模式