在C#中,extern关键字用于声明一个外部方法,即一个由其他语言编写的函数或方法。外部方法可以通过使用DllImport属性来引用一个外部库中的函数。以下是extern关键字的用法示例:
usingSystem;
usingSystem.Runtime.InteropServices;
classProgram
{
//声明外部方法
[DllImport("user32.dll",SetLastError=true)]
publicstaticexternintMessageBox(IntPtrhWnd,stringtext,stringcaption,uinttype);
staticvoidMain()
{
//调用外部方法
MessageBox(IntPtr.Zero,"HelloWorld!","MessageBox",0);
}
}
在上面的示例中,通过extern关键字声明了一个外部方法MessageBox,并使用DllImport属性引用了user32.dll库中的MessageBox函数。在Main方法中调用了MessageBox方法来显示一个消息框。