“static this()”是什么意思?类外是什么意思?

发布于 2024-11-12 03:11:29 字数 239 浏览 1 评论 0原文

我非常了解静态构造函数,但是在类之外使用 static this() 意味着什么?

import std.stdio;

static this(){

  int x = 0;

}


int main(){

  writeln(x); // error

  return 0;
}

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

I'm very well aware of static constructors, but what does it mean to have a static this() outside of a class?

import std.stdio;

static this(){

  int x = 0;

}


int main(){

  writeln(x); // error

  return 0;
}

And how do I access the variables define in static this() ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心凉 2024-11-19 03:11:29

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

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

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.");
}

这些函数的目的基本上是初始化和取消初始化全局变量。

It's a module constructor. That code is run once for each thread (including the main thread).

There are also module destructors as well as shared module constructors and destructors:

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.");
}

The purpose of these is basically to initialise and deinitialise global variables.

離殇 2024-11-19 03:11:29

这是模块构造函数。您可以在这里阅读有关它们的信息:http://www.digitalmars.com/d/2.0/ module.html

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

This is the module constructor. You can read about them here: http://www.digitalmars.com/d/2.0/module.html

Obviously, you can't access x in your sample, because it's a module constructor's local variable, just as well as you couldn't have done it with a class constructor's one. But you can access module-scope globals there (and initialise them, which is what the module constructors are for).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文