修饰符:extern

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

[DllImport("avifil32.dll")]
private static extern void AVIFileInit();
本在线速查手册由www.w♡3♡x♡u♡e.com提供,请勿盗用!
说明:

extern 关键字还可以定义外部程序集别名,使得可以从单个程序集中引用同一组件的不同版本。有关更多信息,请参见 外部别名(C# 参考)

本在线速查手册由www.w♡3♡x♡u♡e.com提供,请勿盗用!

将 abstract(C# 参考)和 extern 修饰符一起使用来修改同一成员是错误的。使用 extern 修饰符意味着方法在 C# 代码的外部实现,而使用 abstract 修饰符意味着在类中未提供方法实现。

说明:

extern 关键字在使用上比在 C++ 中有更多限制。若要与 C++ 关键字进行比较,请参见 C++ Language Reference 中的 Using extern to Specify Linkage

本在线速查手册由www.w♡3♡x♡u♡e.com提供,请勿盗用!

示例

在该示例中,程序接收来自用户的字符串并将该字符串显示在消息框中。程序使用从 User32.dll 库导入的 MessageBox 方法。

C#
//using System.Runtime.InteropServices;
class ExternTest
{
    [DllImport("User32.dll", CharSet=CharSet.Unicode)] 
    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);
    }

}


本在线速查手册由www.w♡3♡x♡u♡e.com提供,请勿盗用!

此示例使用 C 程序创建一个 DLL,在下一示例中将从 C# 程序调用该 DLL。

// cmdll.c
// Compile with: /LD
int __declspec(dllexport) SampleMethod(int i)
{
   return i*10;
}
本在线速查手册由www.w♡3♡x♡u♡e.com提供,请勿盗用!

该示例使用两个文件 CM.cs 和 Cmdll.c 来说明 extern。C 文件是示例 2 中创建的外部 DLL,它从 C# 程序内调用。

// cm.cs
using System;
using System.Runtime.InteropServices;
public class MainClass 
{
   [DllImport("Cmdll.dll")]
   public static extern int SampleMethod(int x);

   static void Main() 
   {
      Console.WriteLine("SampleMethod() returns {0}.", SampleMethod(5));
   }
}
本在线速查手册由www.w♡3♡x♡u♡e.com提供,请勿盗用!
SampleMethod() returns 50.
本在线速查手册由www.w♡3♡x♡u♡e.com提供,请勿盗用!

备注

生成项目:

这将创建可执行文件 CM.exe。运行此程序时,SampleMethod 将值 5 传递到 DLL 文件,该文件将此值乘以 10 返回。