可以选择为 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 系统的运行时。 但是,对于 Unix 系统,将在运行时使用 runtimes\unix\lib\net6.0\A.dll
。
尝试打包此项目时,会出现以下错误:
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]
你意识到了你的错误,并在 Unix 运行时中也添加了 A.B.Open(string)
。
#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
你再次尝试打包项目,结果成功。
严格模式
可以通过在项目文件中设置EnableStrictModeForCompatibleTfms
来为此验证程序启用严格模式。 启用严格模式会更改一些规则,在获取差异时将执行一些其他规则。 如果希望所比较的双方在领域和标识方面完全相同,这十分有用。 有关详细信息,请参阅 “严格”模式。