D:如何从主窗口退出



终止/退出main函数的方法是什么?

import std.stdio;
import core.thread;
void main()
{
    int i;
    while (i <= 5)
    {
        writeln(i++);
        core.thread.Thread.sleep( dur!("seconds")(1) );
    }
    if (i == 5) 
    {
        writeln("Exit");
        return; // I need terminate main, but it's look like break do exit only from scope
    }
    readln(); // it's still wait a user input, but I need exit from App in previous step
}

我试着用谷歌搜索,发现下一个问题D退出声明建议使用C退出函数。在现代D中有没有新的未来,可以让它更优雅?

如果你不做紧急出口,那么你想要清理一切。我为此创建了一个ExitException:

class ExitException : Exception
{
    int rc;
    @safe pure nothrow this(int rc, string file = __FILE__, size_t line = __LINE__)
    {
        super(null, file, line);
        this.rc = rc;
    }
}

你编写main()函数然后像

int main(string[] args)
{
    try
    {
        // Your code here
    }
    catch (ExitException e)
    {
        return e.rc;
    }
    return 0;
}

在需要退出时调用

throw new ExitException(1);

导入stdlib并在传递0时调用exit。

 import std.c.stdlib;
    exit(0);

最新更新