当方法声明包含extern修饰符时,称该方法为外部方法。外部方法是在外部实现的,编程语言通常是使用C#以外的语言。外部方法不可以是泛型。
extern修饰符通常与DllImport属性一起使用,从而使外部方法可以由DLL(动态链接阵)实现。执行环境可以支持其他用来提供外部方法实现的机制。当外部方法包含DllImport属性时,该方法声明必须同时包含一个static修饰符。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication7
{
//方法位置:通常在类当中,并且与其他方法保持平级关系
class Program
{
//使用之前应该引入命名空间:System.Runtime.InteropServices
[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\n"+"欢迎来到这里","提示",0);
Console.ReadKey();
}
}
}