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

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

已引入的版本

.NET 10

以前的行为

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

例如,使用以下代码,运行时将搜索程序集目录,然后回退到 OS 搜索路径。

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

新行为

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

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

破坏性变更的类型

这是行为 变化

更改原因

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

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

示例:

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

受影响的 API

另请参阅