D 什么是;静态此();课外活动是什么意思?

D 什么是;静态此();课外活动是什么意思?,d,D,我非常了解静态构造函数,但是在类之外有一个static this()意味着什么呢 import std.stdio; static this(){ int x = 0; } int main(){ writeln(x); // error return 0; } 如何访问静态this()中定义的变量?这是模块构造函数。您可以在此处阅读有关它们的信息: 显然,您不能访问示例中的x,因为它是模块构造函数的局部变量,就像您不能使用类构造函数的局部变量一样。但是您可以在那里访

我非常了解静态构造函数,但是在类之外有一个
static this()
意味着什么呢

import std.stdio;

static this(){

  int x = 0;

}


int main(){

  writeln(x); // error

  return 0;
}

如何访问
静态this()
中定义的变量?

这是模块构造函数。您可以在此处阅读有关它们的信息:


显然,您不能访问示例中的
x
,因为它是模块构造函数的局部变量,就像您不能使用类构造函数的局部变量一样。但是您可以在那里访问模块作用域全局变量(并初始化它们,这就是模块构造函数的用途)。

它是一个模块构造函数。该代码对每个线程(包括主线程)运行一次

还有模块析构函数以及共享模块构造函数和析构函数:

static this()
{
   writeln("This is run on the creation of each thread.");
}

static ~this()
{
   writeln("This is run on the destruction of each thread.");
}

shared static this()
{
   writeln("This is run once at the start of the program.");
}

shared static ~this()
{
   writeln("This is run once at the end of the program.");
}
其目的基本上是初始化和取消初始化全局变量