题目描述
利用extern修饰符和DllImport属性调用"User32.dll"实例自定义信息提示框的内容。(控制台应用程序)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices;//引入命名空间 namespace 外部方法 { //方法位置:通常类当中,并且与其他方法保持平级关系 class Program { [DllImport("User32.dll")] //声明外部方法,使用关键字extern由于配合DllImport属性使用,所以必须包含static关键字 public static extern int MessageBox(int h, string m, string c, int type); static int Main(string[] args) { Console.WriteLine("请输入您的姓名:"); string name = Console.ReadLine(); //利用return进行弹出对话框,所以需要将Main方法改为有返回值 return MessageBox(0,"您好:"+name+"\n"+"欢迎阅读本篇文章","欢迎提示",0); } } }
***当方法声明包含extern修饰符时,称该方法为外部方法。外部方法是在外部实现的。外部方法不可以时泛型。
extern修饰符通常与DllImport属性一起使用,从而使外部方法可以由DLL(动态链接阵)实现。执行环境可以支持其他用来提供外部方法实现的机制。当外部方法包含DllImport属性时,该方法必须同时包含一个static修饰符。