指定 DllImportSearchPath.AssemblyDirectory 仅搜索程序集目录

从 .NET 10 开始,如果指定 DllImportSearchPath.AssemblyDirectory 为唯一的搜索标志,运行时将在程序集目录中独占搜索。 此更改会影响 P/Invokes 和 NativeLibrary 类的行为。

已引入的版本

.NET 10 预览版 5

以前的行为

DllImportSearchPath.AssemblyDirectory 作为唯一的搜索标志指定时,运行时首先搜索程序集目录。 如果未找到该库,它将回退到作系统的默认库搜索行为。

示例:

[DllImport("example.dll", DllImportSearchPath = DllImportSearchPath.AssemblyDirectory)]
public static extern void ExampleMethod();

在这种情况下,运行时将搜索程序集目录,然后退回到操作系统搜索路径。

新行为

DllImportSearchPath.AssemblyDirectory 被指定为唯一的搜索标志时,运行时仅在程序集目录中搜索。 它不会回归到操作系统的默认库搜索行为。

前面的代码示例现在仅搜索程序集的目录以查找 example.dll。 如果未找到库,将抛出一个 DllNotFoundException 异常。

破坏性变更的类型

这是行为 变化

更改原因

指定 DllImportSearchPath.AssemblyDirectory 时的回退行为导致混淆,并且与搜索标志的设计不一致。 此更改可确保行为清晰和一致性。

如果需要回退行为,请避免指定显式 DllImportSearchPath。 默认情况下,如果未指定任何标志,运行时将搜索程序集目录,然后回退到作系统的默认库搜索行为。

示例:

[DllImport("example.dll")]
public static extern void ExampleMethod();

受影响的 API