您可以選擇針對 NuGet 套件中的不同運行時間使用不同的實作元件。 在此情況下,您必須確定這些元件彼此之間相容,並且與編譯時間元件相容。
例如,請考慮下列案例。 您正在開發與 Unix 和 Windows API 的互操作呼叫相關的函式庫。 您已撰寫下列程式代碼:
#if Unix
public static void Open(string path, bool securityDescriptor)
{
// Call Unix specific stuff.
}
#else
public static void Open(string path)
{
// Call Windows specific stuff.
}
#endif
產生的封裝結構如下所示。
lib/net6.0/A.dll
runtimes/unix/lib/net6.0/A.dll
lib\net6.0\A.dll 不論基礎作系統為何,一律會在編譯階段使用。
lib\net6.0\A.dll 也用於非 Unix 系統的執行時。 不過,runtimes\unix\lib\net6.0\A.dll 在 Unix 系統的執行時期會被使用。
當您嘗試封裝此專案時,您會收到下列錯誤:
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
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.Open(string)' exists on lib/net6.0/PackageValidationThrough.dll but not on runtimes/unix/lib/net6.0/PackageValidationThrough.dll [D:\demo\PackageValidationThrough.csproj]
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.Open(string, bool)' exists on runtimes/unix/lib/net6.0/PackageValidationThrough.dll but not on lib/net6.0/PackageValidationThrough.dll [D:\demo\PackageValidationThrough.csproj]
您意識到了您的錯誤,並將 A.B.Open(string) 新增至 Unix 運行時。
#if Unix
public static void Open(string path, bool securityDescriptor)
{
// Call Unix specific stuff.
}
public static void Open(string path)
{
throw new PlatformNotSupportedException();
}
#else
public static void Open(string path)
{
// Call Windows specific stuff.
}
public static void Open(string path, bool securityDescriptor)
{
throw new PlatformNotSupportedException();
}
#endif
您再次嘗試封裝專案,成功了。
Strict 模式
您可以在項目檔中設定 ,以啟用此驗證器的EnableStrictModeForCompatibleTfms。 啟用嚴格模式會變更某些規則,而取得差異時將會執行一些其他規則。 當您希望比較的兩邊在表面積和特性上嚴格相同時,這會很有用。 如需詳細資訊,請參閱 Strict 模式。