问题
I've done some reading here, and here and I'm still confused about if I should use Enviorment.Exit() in my console application.
In a method, I have the following code if the user types exit at the prompt,
if(userSelect == "exit"){
{
Environment.Exit(0);
}
Update:
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Welcome to my Console App");
Console.WriteLine();
consoleManager();
}
public static void consoleManager()
{
string consolePrompt="ConsoleApp">";
string whichMethod="";
Console.Write(consolePrompt);
whichMethod = Console.ReadLine();
if(whichMethod == "view enties")
{
viewEntry();
}
else
if(whichMethod == "Add Entry")
{
addEntry();
}
else
if(whichMethod == "exit"){
{
//what to do here
}
}
else{
help();
}
}
回答1:
Go through the MSDN Documentation for - Environment.Exit, it explains the paramter
the exitCode parameter, use a non-zero number to indicate an error. In your application, you can define your own error codes in an enumeration, and return the appropriate error code based on the scenario. For example, return a value of 1 to indicate that the required file is not present, and a value of 2 to indicate that the file is in the wrong format.
So if you say Exit(0), you will say your process exited successfully without any error. If you use any System Error Code, you are notifying the operating system what when wrong. In your case Environment.Exit(0) is sufficient.
Edit I am pretty sure, you are overthinking it. Points to consider -
- If you are exiting from Main a simple return statement would be sufficient.
- Elsewhere use Enviorment.Exit(), because return statement will return you to the Main method and program will still continue to run.
- I hope you are familiar with
void Main(string[] args)andint Main(string[] args). The difference is the return value. You use it incase you want to return a error code, 0 for success and other numbers for various errors. You can very well use the System Error Code linked above. - It boils down to the point - if the caller of your console program uses the return value or not. If its a dos prompt where you are running it will be ignored. If some external application is running your console it may process your output.
来源:https://stackoverflow.com/questions/35393877/correct-way-to-exit-from-console-application