extern 修饰符用于声明在外部实现的方法。extern 关键字常用于定义外部程序集别名,使得可以从单个程序集中引用同一组件的不同版本。
extern 修饰符的常见用法是在使用 Interop 服务调入非托管代码时与 DllImport 属性一起使用;在这种情况下,该方法还必须声明为 static。如:
[DllImport("avifil32.dll")]
private static extern void AVIFileInit();
在该示例中,程序接收来自用户的字符串并将该字符串显示在消息框中。程序使用从
User32.dll库导入的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); } }
本文介绍如何使用extern关键字声明外部方法,并通过DllImport属性调用非托管代码。具体示例展示了如何从User32.dll库导入MessageBox方法来显示用户输入的消息。
533

被折叠的 条评论
为什么被折叠?



