您现在的位置: 万盛学电脑网 >> 程序编程 >> 网络编程 >> 编程语言综合 >> 正文

C# extern 修饰符的用法

作者:佚名    责任编辑:admin    更新时间:2022-06-22

   extren主要用于声明在外部实现的方法,什么叫外部实现的方法呢,一般说来就是用System.Runtime.InteropServices服务的DllImport方法引入非托管代码程序集。例如调用程序API,C语言写的方法等等。在这种情况下,声明必须为static

  同时,extren关键字还可以定义外部程序集别名,使得可以从单个程序集中引用同一组件的不同版本。

  下面是一个改写自MSDN上的简单的例子,调用系统winmm.DLL播放wav文件:

  //系统API的调用的声明

  [System.Runtime.InteropServices.DllImport("winmm.DLL", EntryPoint = "PlaySound", SetLastError = true)]

  public static extern void PlaySound(string path,System.IntPtr hMod,PlaySoundFlags flags);

  //调用该方法

  string path = @“c:22.wav”;

  try

  {

  PlaySound(path, new System.IntPtr(), PlaySoundFlags.SND_SYNC);

  }

  catch (Exception ex)

  {

  throw (ex);

  }