c# extern修饰符用于声明在外部实现的方法。本文就介绍了C# Extern修饰符的使用。
c# extern 修饰符的常见用法是在运用 Interop 服务调入非保管代码时与 DllImport 特点一同运用;在这种情况下,该办法还必须声明为 static,如下面的示例所示:
- [DllImport("avifil32.dll")]
- privatestaticexternvoidAVIFileInit();
留意
extern 关键字还能够界说外部程序集别号,使得能够从单个程序会集引证同一组件的不同版别。
将 abstract 和 extern 修饰符一同运用来修正同一成员是过错的。
运用
c# extern 修饰符意味着办法在 C# 代码的外部完成,而运用 abstract 修饰符意味着在类中未供给办法完成。留意 extern 关键字在运用上比在 C++ 中有更多的约束。
示例
在该示例中,程序接纳来自用户的字符串并将该字符串显现在音讯框中。程序运用从 User32.dll库导入的 MessageBox 办法。
- usingSystem;usingSystem.Runtime.InteropServices;
- classMainClass
- {
- [DllImport("User32.dll")]
- publicstaticexternintMessageBox(inth,stringm,stringc,inttype);
- staticintMain()
- {
- stringmyString;
- Console.Write("Enteryourmessage:");
- myString=Console.ReadLine();
- returnMessageBox(0,myString,"MyMessageBox",0);
- }
- }
- 此示例运用C程序创立一个DLL,鄙人一示例中将从C#程序调用该DLL。
- //cmdll.c//compilewith:
- /LDint__declspec(dllexport)SampleMethod(inti)
- {
- returni*10;
- }
该示例运用两个文件 CM.cs 和 Cmdll.c 来阐明 extern。
C 文件是示例 2 中创立的外部 DLL,它从C# 程序内调用。
- //cm.csusingSystem;
- usingSystem.Runtime.InteropServices;
- publicclassMainClass{
- [DllImport("Cmdll.dll")]
- publicstaticexternintSampleMethod(intx);
- staticvoidMain()
- {
- Console.WriteLine("SampleMethod()returns{0}.",SampleMethod(5));
- }
- }
输出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修饰符的效果介绍到这儿。
【修改引荐】
- 解密C#-SQLite是怎么移植的
- 看看怎么透过JavaScript调用C#函数
- 浅析C#事情注册和刊出
- 示例:C#经过AMO目标阅读SQL SERVER 2005 SSAS
- C#躲藏窗口的几种办法
转载请说明出处
知优网 » 简介C# Extern修饰符的效果(extern修饰函数)
知优网 » 简介C# Extern修饰符的效果(extern修饰函数)