從 .NET 10 開始,如果您指定 DllImportSearchPath.AssemblyDirectory 作為唯一的搜尋旗標,執行階段只會在組件目錄中搜尋。 這項變更會影響 P/Invokes 和 類別 NativeLibrary 的行為。
推出的版本
.NET 10
先前的行為
先前,當 DllImportSearchPath.AssemblyDirectory 被指定為唯一的搜尋旗標時,執行階段會首先搜尋元件目錄。 如果找不到函式庫,會退回使用作業系統的默認函式庫搜尋行為。
例如,使用下列程式代碼,執行階段會搜尋元件目錄,然後退回到操作系統搜尋路徑。
[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
- 使用 P/Invokes DefaultDllImportSearchPathsAttribute
- System.Runtime.InteropServices.NativeLibrary.Load
- System.Runtime.InteropServices.NativeLibrary.TryLoad