共用方式為


驗證相容的架構

包含相容架構的套件必須確保針對其中一個編譯的程式代碼可以針對另一個程式代碼執行。 相容的架構組範例包括:

  • .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.
    }

您再次嘗試封裝專案,成功了。

相容框架成功

Strict 模式

您可以在項目檔中設定 ,以啟用此驗證器的EnableStrictModeForCompatibleFrameworksInPackage。 啟用嚴格模式會變更某些規則,並在取得差異時執行一些其他規則。 當您希望比較的兩邊在表面積和特性上嚴格相同時,這會很有用。 如需詳細資訊,請參閱 Strict 模式