跳轉到內容

C# 程式設計/關鍵字/extern

來自 Wikibooks,開放的書籍,面向開放的世界

關鍵字 extern 表示正在呼叫的方法存在於 DLL 中。

一個名為 tlbimp.exe 的工具可以建立一個包裝程式集,允許 C# 與 DLL 互動,就像它是一個 .NET 程式集一樣,即使用建構函式例項化它,呼叫它的方法。

舊的 DLL 不適用於此方法。相反,您必須明確告訴編譯器要呼叫哪個 DLL,要呼叫哪個方法以及要傳遞哪些引數。由於引數型別非常重要,您還可以顯式定義應將什麼型別傳遞給方法作為引數。

以下是一個示例

using System;
using System.Runtime.InteropServices;

namespace ExternKeyword
{
     public class Program
     {
          static void Main()
          {
               NativeMethods.MessageBoxEx(IntPtr.Zero, "Hello there", "Caption here", 0, 0);
          }
     }
  
     public class NativeMethods
     {
          [DllImport("user32.dll")]
          public static extern MessageBoxEx(IntPtr hWnd, string lpText, string lpCaption, uint uType, short wLanguageId);
     }
}

[DllImport("user32.dll")] 告訴編譯器要引用哪個 DLL。Windows 按 PATH 環境變數定義的方式搜尋檔案,因此將在失敗之前搜尋這些路徑。

該方法也是靜態的,因為 DLL 可能不理解如何被“建立”,因為 DLL 可以用不同的語言建立。這允許直接呼叫該方法,而不是例項化它然後使用它。


C# 關鍵字
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using var virtual
void volatile while
特殊的 C# 識別符號(上下文關鍵字)
add alias async await dynamic
get global nameof partial remove
set value when where yield
上下文關鍵字(用於查詢)
ascending by descending equals from
group in into join let
on orderby select where
華夏公益教科書