什么是退出一个命令行程序的preferred方式?命令行、方式、程序、preferred

2023-09-03 04:55:14 作者:一切解释都是多余

这应该是简单的。我只需要简单地退出我的命令行的C#程序 - 没有花哨的东西

This should be straightforward. I just need to simply exit my commandline c# program - no fancy stuff.

我应该使用

Environment.Exit();

this.Close();

或其他什么东西?

or something else?

推荐答案

使用返回; 主要方法。照片 如果您不是在main方法,当你决定要退出程序,你需要从目前执行的主要方法,该方法返回。

Use return; in your Main method. If you aren't in the main method when you decide to exit the program, you need to return from the method that Main method currently executes.

例如:

void Main(...)
{
    DisplayAvailableCommands();
    ProcessCommands();
}

void ProcessCommands()
{
    while(true)
    {
        var command = ReadCommandFromConsole();
        switch(command)
        {
            case "help":
                DisplayHelp();
                break;
            case "exit":
                return;
        }
    }
}

这是不是一个真正的控制台应用程序的良好的整体设计的一个例子,但它说明了这一点。

This is not really an example of good overall design of a console application, but it illustrates the point.