c# extern修饰符用于声明在外部实现的方法。本文就介绍了C# Extern修饰符的使用。

C# Extern修饰符用于声明在外部完成的办法。

简介C# Extern修饰符的效果(extern修饰函数)  C# Extern修饰符 第1张

c# extern 修饰符的常见用法是在运用 Interop 服务调入非保管代码时与 DllImport 特点一同运用;在这种情况下,该办法还必须声明为 static,如下面的示例所示:

  1. [DllImport("avifil32.dll")]
  2. privatestaticexternvoidAVIFileInit();

留意

extern 关键字还能够界说外部程序集别号,使得能够从单个程序会集引证同一组件的不同版别。

将 abstract 和 extern 修饰符一同运用来修正同一成员是过错的。

运用

c# extern 修饰符意味着办法在 C# 代码的外部完成,而运用 abstract 修饰符意味着在类中未供给办法完成。留意 extern 关键字在运用上比在 C++ 中有更多的约束。

示例

在该示例中,程序接纳来自用户的字符串并将该字符串显现在音讯框中。程序运用从 User32.dll库导入的 MessageBox 办法。

  1. usingSystem;usingSystem.Runtime.InteropServices;
  2. classMainClass
  3. {
  4. [DllImport("User32.dll")]
  5. publicstaticexternintMessageBox(inth,stringm,stringc,inttype);
  6. staticintMain()
  7. {
  8. stringmyString;
  9. Console.Write("Enteryourmessage:");
  10. myString=Console.ReadLine();
  11. returnMessageBox(0,myString,"MyMessageBox",0);
  12. }
  13. }
  14. 此示例运用C程序创立一个DLL,鄙人一示例中将从C#程序调用该DLL。
  15. //cmdll.c//compilewith:
  16. /LDint__declspec(dllexport)SampleMethod(inti)
  17. {
  18. returni*10;
  19. }

该示例运用两个文件 CM.cs 和 Cmdll.c 来阐明 extern。

C 文件是示例 2 中创立的外部 DLL,它从C# 程序内调用。

  1. //cm.csusingSystem;
  2. usingSystem.Runtime.InteropServices;
  3. publicclassMainClass{
  4. [DllImport("Cmdll.dll")]
  5. publicstaticexternintSampleMethod(intx);
  6. staticvoidMain()
  7. {
  8. Console.WriteLine("SampleMethod()returns{0}.",SampleMethod(5));
  9. }
  10. }

输出SampleMethod() returns 50. 补白生成项目: 运用 Visual C++ 指令即将 Cmdll.c 编译为 DLL: cl /LD Cmdll.c 运用指令行编译 CM.cs: csc CM.cs 这将创立可执行文件 CM.exe。运转此程序时,SampleMethod 将值 5 传递到 DLL 文件,该文件将此值乘以 10 回来。

好了,C# Extern修饰符的效果介绍到这儿。

【修改引荐】

  1. 解密C#-SQLite是怎么移植的
  2. 看看怎么透过JavaScript调用C#函数
  3. 浅析C#事情注册和刊出
  4. 示例:C#经过AMO目标阅读SQL SERVER 2005 SSAS
  5. C#躲藏窗口的几种办法
转载请说明出处
知优网 » 简介C# Extern修饰符的效果(extern修饰函数)

发表评论

您需要后才能发表评论