简介C# Extern修饰符的作用

开发 后端
c# extern修饰符用于声明在外部实现的方法。本文就介绍了C# Extern修饰符的使用。

c# extern修饰符用于声明在外部实现的方法。

c# extern 修饰符的常见用法是在使用 Interop 服务调入非托管代码时与 DllImport 属性一起使用;在这种情况下,该方法还必须声明为 static,如下面的示例所示:

  1. [DllImport("avifil32.dll")]  
  2. private static extern void AVIFileInit(); 

注意

extern 关键字还可以定义外部程序集别名,使得可以从单个程序集中引用同一组件的不同版本。

将 abstract 和 extern 修饰符一起使用来修改同一成员是错误的。

使用

c# extern 修饰符意味着方法在 C# 代码的外部实现,而使用 abstract 修饰符意味着在类中未提供方法实现。注意 extern 关键字在使用上比在 C++ 中有更多的限制。

示例

在该示例中,程序接收来自用户的字符串并将该字符串显示在消息框中。程序使用从 User32.dll库导入的 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 程序创建一个 DLL,在下一示例中将从 C# 程序调用该 DLL。  
  15. // cmdll.c // compile with:   
  16. /LD int __declspec(dllexport) SampleMethod(int i)   
  17. {  
  18. return i*10;  
  19. }  

该示例使用两个文件 CM.cs 和 Cmdll.c 来说明 extern。

C 文件是示例 2 中创建的外部 DLL,它从C# 程序内调用。

  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. 备注生成项目: 使用 Visual C++ 命令行将 Cmdll.c 编译为 DLL: cl /LD Cmdll.c 使用命令行编译 CM.cs: csc CM.cs 这将创建可执行文件 CM.exe。运行此程序时,SampleMethod 将值 5 传递到 DLL 文件,该文件将此值乘以 10 返回。

 好了,C# Extern修饰符的作用介绍到这里。

【编辑推荐】

  1. 解密C#-SQLite是如何移植的
  2. 看看如何透过JavaScript调用C#函数
  3. 浅析C#事件注册和注销
  4. 示例:C#通过AMO对象浏览SQL SERVER 2005 SSAS
  5. C#隐藏窗口的几种方法
责任编辑:book05 来源: hi.baidu
相关推荐

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-09-02 17:14:28

C#修饰符

2009-08-27 13:06:13

C# new修饰符

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

2011-07-20 16:48:22

C++static

2011-07-20 16:50:39

inlinec++

2011-07-20 16:57:05

C++const

2023-12-29 09:01:27

SwiftUI视图修饰符

2011-06-02 14:51:07

JAVA修饰符

2009-08-12 14:49:33

C#移位运算符

2015-08-18 09:25:11

Java修饰符关键词

2010-01-11 18:46:15

VB.NET修饰符

2009-08-12 14:29:32

C#条件运算符

2009-09-02 17:19:43

C#换行连接符
点赞
收藏

51CTO技术栈公众号