也可用 using 引入名稱空間,不過這非單一引入指定方法,而是引入整個名稱空間或類別。
舉例如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Demo { [System.Runtime.InteropServices.DllImport( "class28.dll" )] public static extern void DoSomething(); static void Main() { DoSomething(); } } /* 《程式語言教學誌》的範例程式 檔名:class27.cs 功能:示範 C# 程式 作者:張凱慶 時間:西元 2013 年 6 月 */ |
這裡用 System.Runtime.InteropServices.DllImport() 載入 dll 檔案
2 | [System.Runtime.InteropServices.DllImport( "class28.dll" )] |
我們提供的 class28.dll 的程式為 class28.cs ,如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | namespace Demo2 { public class Demo3 { public void DoSomething() { System.Console.WriteLine( "There is no spoon." ); } } } /* 《程式語言教學誌》的範例程式 檔名:class28.cs 功能:示範 C# 程式 作者:張凱慶 時間:西元 2013 年 6 月 */ |
先將 class28.cs 編譯為 class28.dll ,然後編譯 class27.cs ,編譯結果是成功的,執行時發生了 DllNotFoundException 的例外,這是找不到 class28.dll 的意思

這是因為 C# 只有在 Windows 平台才開放直接存取相同目錄下的程式庫檔案,其他平台 Mac OX 、 Linux 等都預設限制不得存取存取相同目錄下的程式庫檔案,這變成自己得設定該平台的環境變數唷!相關資訊請參考 Mono 網頁的 Interop with Native Libraries 。
中英文術語對照 | |
---|---|
類別 | class |
程式庫 | library |
方法 | method |
您可以繼續參考
類別
相關目錄
回 C# 快速導覽
回 C# 教材
回首頁
參考資料
Standard ECMA-334 C# Language Specification
msdn: extern (C# 參考)
沒有留言:
張貼留言