自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

簡介C# Extern修飾符的作用

開發(fā) 后端
c# extern修飾符用于聲明在外部實(shí)現(xiàn)的方法。本文就介紹了C# Extern修飾符的使用。

c# extern修飾符用于聲明在外部實(shí)現(xiàn)的方法。

c# extern 修飾符的常見用法是在使用 Interop 服務(wù)調(diào)入非托管代碼時(shí)與 DllImport 屬性一起使用;在這種情況下,該方法還必須聲明為 static,如下面的示例所示:

  1. [DllImport("avifil32.dll")]  
  2. 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 方法。

  1. using System; using System.Runtime.InteropServices;   
  2. class MainClass   
  3. {  
  4. [DllImport("User32.dll")]  
  5. public static extern int MessageBox(int h, string m, string c, int type);  
  6. static int Main()   
  7. {   
  8. string myString;  
  9. Console.Write("Enter your message: ");  
  10. myString = Console.ReadLine();   
  11. return MessageBox(0, myString, "My Message Box", 0);   
  12. }   
  13. }  
  14. 此示例使用 C 程序創(chuàng)建一個(gè) DLL,在下一示例中將從 C# 程序調(diào)用該 DLL。  
  15. // cmdll.c // compile with:   
  16. /LD int __declspec(dllexport) SampleMethod(int i)   
  17. {  
  18. return i*10;  
  19. }  

該示例使用兩個(gè)文件 CM.cs 和 Cmdll.c 來說明 extern。

C 文件是示例 2 中創(chuàng)建的外部 DLL,它從C# 程序內(nèi)調(diào)用。

  1. // cm.cs using System;   
  2. using System.Runtime.InteropServices;   
  3. public class MainClass {  
  4. [DllImport("Cmdll.dll")]   
  5. public static extern int SampleMethod(int x);  
  6. static void Main()  
  7. {   
  8. Console.WriteLine("SampleMethod() returns {0}.", SampleMethod(5));   
  9. }   
  10. }  

輸出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修飾符的作用介紹到這里。

【編輯推薦】

  1. 解密C#-SQLite是如何移植的
  2. 看看如何透過JavaScript調(diào)用C#函數(shù)
  3. 淺析C#事件注冊和注銷
  4. 示例:C#通過AMO對象瀏覽SQL SERVER 2005 SSAS
  5. C#隱藏窗口的幾種方法
責(zé)任編輯:book05 來源: hi.baidu
相關(guān)推薦

2009-08-27 11:04:08

C# extern修飾

2009-08-24 16:49:39

C#修飾符

2009-08-21 13:58:06

C# virtual修

2009-08-27 11:12:03

C# abstract

2009-08-27 13:06:13

C# new修飾符

2009-09-02 17:14:28

C#修飾符

2009-08-27 11:16:40

C# sealed修飾

2009-09-04 11:06:40

C#訪問修飾符

2011-06-28 09:29:11

C#修飾符

2011-05-13 14:56:14

autoregisterstatic

2024-09-27 09:50:11

C#正則表達(dá)式

2011-07-20 16:50:39

inlinec++

2011-07-20 16:48:22

C++static

2011-07-20 16:57:05

C++const

2023-12-29 09:01:27

SwiftUI視圖修飾符

2009-09-02 17:19:43

C#換行連接符

2009-08-12 13:35:22

C#關(guān)系運(yùn)算符

2009-08-12 14:29:32

C#條件運(yùn)算符

2009-08-12 14:49:33

C#移位運(yùn)算符

2011-06-02 14:51:07

JAVA修飾符
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號