共用方式為


extern (C# 參考)

更新:2007 年 11 月

extern 修飾詞是用來宣告外部實作的方法。extern 修飾詞的常見用法,是在使用 Interop 服務進行 Unmanaged 程式碼呼叫時,搭配 DllImport 屬性 (Attribute) 使用。在此情況下,此方法也必須宣告為 static,如下列範例所示:

[DllImport("avifil32.dll")]
private static extern void AVIFileInit();
注意事項:

extern 關鍵字也可以定義外部組件 (Assembly) 的別名 (Alias),這樣便能從單一組件中參考相同元件的不同版本。如需詳細資訊,請參閱外部別名 (C# 參考)

同時使用 abstract (C# 參考) 和 extern 修飾詞修改同一個成員是錯誤的。使用 extern 修飾詞,表示該方法是在 C# 程式碼外部實作,而使用 abstract 修飾詞則表示類別 (Class) 中並未提供該方法實作。

注意事項:

extern 關鍵字的用法比在 C++ 中具有更多限制。若要暸解與 C++ 關鍵字的比較,請參閱《C++ 語言參考》裡的Using extern to Specify Linkage

範例

在這個範例裡,程式接收來自使用者的字串並且在訊息方塊裡顯示。此程式使用從 User32.dll 程式庫匯入的 MessageBox 方法。

//using System.Runtime.InteropServices;
class ExternTest
{
    [DllImport("User32.dll", CharSet=CharSet.Unicode)] 
    public static extern int MessageBox(int h, string m, string c, int type);

    static int Main()
    {
        string myString;
        Console.Write("Enter your message: ");
        myString = Console.ReadLine();
        return MessageBox(0, myString, "My Message Box", 0);
    }

}

這個範例會從 C 程式建立 DLL,而此 DLL 是從下一個範例中的 C# 程式內叫用。

// cmdll.c
// Compile with: /LD
int __declspec(dllexport) SampleMethod(int i)
{
   return i*10;
}

此範例使用兩個檔案,CM.cs 和 Cmdll.c,來示範 extern。C 檔案是範例 2 中所建立的外部 DLL,它是從 C# 程式內叫用。

// cm.cs
using System;
using System.Runtime.InteropServices;
public class MainClass 
{
   [DllImport("Cmdll.dll")]
   public static extern int SampleMethod(int x);

   static void Main() 
   {
      Console.WriteLine("SampleMethod() returns {0}.", SampleMethod(5));
   }
}

SampleMethod() returns 50.

備註

若要建置專案:

  • 使用 Visual C++ 命令列將 Cmdll.c 編譯成 DLL:

    cl /LD Cmdll.c

  • 使用命令列編譯 CM.cs:

    csc CM.cs

這會建立可執行檔 CM.exe。當您執行此程式時,SampleMethod 會將值 5 傳入 DLL 檔,並傳回乘以 10 的值。

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格中的下列章節:

  • 10.6.7 外部方法

請參閱

概念

C# 程式設計手冊

參考

C# 關鍵字

修飾詞 (C# 參考)

System.Runtime.InteropServices.DllImportAttribute

其他資源

C# 參考