簡介C# Extern修飾符的作用
c# extern修飾符用于聲明在外部實(shí)現(xiàn)的方法。
c# extern 修飾符的常見用法是在使用 Interop 服務(wù)調(diào)入非托管代碼時(shí)與 DllImport 屬性一起使用;在這種情況下,該方法還必須聲明為 static,如下面的示例所示:
- [DllImport("avifil32.dll")]
- private static extern void AVIFileInit();
注意
extern 關(guān)鍵字還可以定義外部程序集別名,使得可以從單個(gè)程序集中引用同一組件的不同版本。
將 abstract 和 extern 修飾符一起使用來修改同一成員是錯(cuò)誤的。
使用
c# extern 修飾符意味著方法在 C# 代碼的外部實(shí)現(xiàn),而使用 abstract 修飾符意味著在類中未提供方法實(shí)現(xiàn)。注意 extern 關(guān)鍵字在使用上比在 C++ 中有更多的限制。
示例
在該示例中,程序接收來自用戶的字符串并將該字符串顯示在消息框中。程序使用從 User32.dll庫導(dǎo)入的 MessageBox 方法。
- using System; using System.Runtime.InteropServices;
- class MainClass
- {
- [DllImport("User32.dll")]
- 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 程序創(chuàng)建一個(gè) DLL,在下一示例中將從 C# 程序調(diào)用該 DLL。
- // cmdll.c // compile with:
- /LD int __declspec(dllexport) SampleMethod(int i)
- {
- return i*10;
- }
該示例使用兩個(gè)文件 CM.cs 和 Cmdll.c 來說明 extern。
C 文件是示例 2 中創(chuàng)建的外部 DLL,它從C# 程序內(nèi)調(diào)用。
- // 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. 備注生成項(xiàng)目: 使用 Visual C++ 命令行將 Cmdll.c 編譯為 DLL: cl /LD Cmdll.c 使用命令行編譯 CM.cs: csc CM.cs 這將創(chuàng)建可執(zhí)行文件 CM.exe。運(yùn)行此程序時(shí),SampleMethod 將值 5 傳遞到 DLL 文件,該文件將此值乘以 10 返回。
好了,C# Extern修飾符的作用介紹到這里。
【編輯推薦】