我非常瞭解靜態構造函數,但是在類的外部有一個static this()
是什麼意思?一個類之外的「static this()」是什麼意思?
import std.stdio;
static this(){
int x = 0;
}
int main(){
writeln(x); // error
return 0;
}
如何訪問static this()
中定義的變量?
我非常瞭解靜態構造函數,但是在類的外部有一個static this()
是什麼意思?一個類之外的「static this()」是什麼意思?
import std.stdio;
static this(){
int x = 0;
}
int main(){
writeln(x); // error
return 0;
}
如何訪問static this()
中定義的變量?
這是模塊構造函數。你可以在這裏閱讀:http://www.digitalmars.com/d/2.0/module.html
顯然,你不能在你的示例中訪問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.");
}
的這些目的基本上是初始化和deinitialise全局變量。