【问题标题】:Purpose of C# constructor extern modifierC# 构造函数外部修饰符的用途
【发布时间】:2010-03-05 09:15:32
【问题描述】:

C#构造函数extern修饰符的作用是什么?

我知道使用 extern METHODS 来调用 Win32 函数,但是 CONSTRUCTORS 呢?

请举个实际例子。

注意这一点:

class MyClass
{
    public extern MyClass();
}

【问题讨论】:

  • 请举例说明你的意思。
  • 我认为 MSDN 版本的定义和示例会有所帮助吗? msdn.microsoft.com/en-us/library/e59b22c5%28VS.80%29.aspx
  • 但这对构造函数不起作用,也许这是他的问题,但我不确定,因此我希望他详细说明。
  • @Lasse:在 C# 规范第 10.11 段实例构造函数中说构造函数可以是外部的:When a constructor declaration includes an extern modifier, the constructor is said to be an external constructor. Because an external constructor declaration provides no actual implementation, its constructor-body consists of a semicolon. For all other constructors, the constructor-body consists of a block which specifies the statements to initialize a new instance of the class.
  • 好吧,那我就不知道了。考虑到您实际上无法实现构造函数,我看不出这将如何工作。我怀疑这与在其他地方用IL生成代码有关,无论如何,我删除了我的错误答案。

标签: c# .net


【解决方案1】:

我相信 extern ctor 的一个用途/目的是让构造函数在 CLR 本身内实现。如果你使用 Reflector 反汇编 mscorlib.dll 并查看 System.String 类型,你会看到:

[MethodImpl(MethodImplOptions.InternalCall)]
public extern String(char[] value);

这基本上告诉我们字符串类的 (char[]) ctor 是在外部实现的,作为 .net 运行时的一部分

【讨论】:

    【解决方案2】:

    c# 规范here 表明除了私有、内部、受保护和公共之外,还可以使用 extern 并且这是标准的外部参考 - 参见 here。对我来说,这表明构造函数稍后会链接到类中。就像 PInvoke 调用一样。我猜,没有什么可以阻止 c# 编译器实现程序允许链接包含所述外部构造函数的外部 .net .modules。

    我不能举个例子,但我怀疑一种方法是在 MC++ 中实现构造函数,或者实际上只是一个简单的 IL .module。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-27
      • 2018-01-11
      • 2010-09-20
      • 2012-11-12
      • 1970-01-01
      • 2015-09-10
      相关资源
      最近更新 更多