c# - extern 在 C# 中如何工作?

标签 c# .net performance extern modifier

每当我足够深入地研究反射器时,我都会遇到没有源代码的 extern 方法。我在 http://msdn.microsoft.com/en-us/library/e59b22c5(v=vs.80).aspx 阅读了 msdn 文档.我从那篇文章中得到的是必须注入(inject)带有 extern 修饰符的方法。我将其解释为它的工作方式类似于抽象工厂模式。我还注意到我从未见过非静态外部方法。是否需要静态声明(我可以看出这有什么意义)?我仍然在这里猜测,我不确定它实际上是如何工作的。在我看来,编译器必须识别某些减轻处理的属性,但我不知道这些属性是什么,除了我遇到的那些 MethodImplAttributeDllImportAttribute 来自 MSDN 示例。某人如何利用 extern 属性?它说,在许多情况下,这可以提高性能。另外,我将如何着手研究 object.InternalGetEquals()extern 方法的来源?

最佳答案

考虑阅读 C# 规范的第 10.6.7 节,它回答了您的许多问题。为了您的方便,我在这里复制了一部分:


When a method declaration includes an extern modifier, that method is said to be an external method. External methods are implemented externally, typically using a language other than C#. Because an external method declaration provides no actual implementation, the method-body of an external method simply consists of a semicolon. An external method may not be generic. The extern modifier is typically used in conjunction with a DllImport attribute, allowing external methods to be implemented by DLLs (Dynamic Link Libraries). The execution environment may support other mechanisms whereby implementations of external methods can be provided. When an external method includes a DllImport attribute, the method declaration must also include a static modifier.


How does someone leverage the extern attribute?

  • 使用您选择的非托管语言编写代码。
  • 将其编译成 DLL,导出代码的入口点。
  • 制作一个互操作库,将方法定义为给定 DLL 中的外部方法。
  • 从 C# 调用它。
  • 利润!

How would I go about looking into the source of extern methods like Object.InternalGetEquals()?

转到 https://github.com/dotnet/coreclr/tree/master/src/vm

关于c# - extern 在 C# 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5110706/

相关文章:

c# - 静态属性的默认值

c# - 使用RX同步多个事件

c# - 是否可以在一行代码中使用一个 LINQ

c# - 形成两个列表并集的最简单方法

sql - 提高 SQL CTE 查询性能

java - 在 Java 应用程序中存储大量类似字典的数据

c# - DBContext 不包含条目 : Cannot load related data 的定义

c# - 如何检查应用程序是否有权访问目录?

c# - 方法/构造函数中的集合参数?

MYSQL INNER JOIN 使用索引很慢