且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

退出控制台应用程序的正确方法

更新时间:2022-03-14 22:59:40

查看有关- Environment.Exit ,它解释了该参数

Go through the MSDN Documentation for - Environment.Exit, it explains the paramter


exitCode参数,使用非零数字表示错误。在
应用程序中,您可以在
枚举中定义自己的错误代码,并根据
场景返回适当的错误代码。例如,返回值1表示所需的
文件不存在,返回值2表示
文件格式错误。

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.

因此,如果您说Exit(0),您将说您的过程成功退出,没有任何错误。如果您使用任何系统错误代码,则您将在操作系统发生错误时通知操作系统。在您的情况下, Environment.Exit(0)就足够了。

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 -


  1. 如果您从Main退出,则简单的return语句就足够了。

  2. 在其他地方使用Enviorment.Exit(),因为return语句将使您返回Main方法,并且程序仍将继续运行。

  3. 我希望您熟悉 void Main(string [] args) int Main(string [] args)。区别在于返回值。如果要返回错误代码,则返回0,成功则返回0,而对于各种错误则返回其他数字。您可以很好地使用上面链接的系统错误代码。

  4. 它可以归结为一个要点-控制台程序的调用者是否使用返回值。如果它在您正在运行的地方出现一个dos提示,它将被忽略。如果某些外部应用程序正在运行您的控制台,则它可能会处理您的输出。

  1. If you are exiting from Main a simple return statement would be sufficient.
  2. Elsewhere use Enviorment.Exit(), because return statement will return you to the Main method and program will still continue to run.
  3. I hope you are familiar with void Main(string[] args) and int 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.
  4. 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.