What's the preferred way of exiting a command

2019-06-15 14:25发布

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

Should I use

Environment.Exit();

or

this.Close();

or something else?

2条回答
趁早两清
2楼-- · 2019-06-15 14:40

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.

Example:

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.

查看更多
对你真心纯属浪费
3楼-- · 2019-06-15 14:56

just return from the Main method.

Edit:

if you really have lost the flow and want to exit from anywhere in the application (like inside any method called by Main), you can use:

Environment.Exit(0);

remember that normally you should return 0 to the calling process (OS) when everything went fine and you return a non zero value if an error happened and execution did not go as smooth as should have been.

查看更多
登录 后发表回答