如何在.NET中指定控制台应用程序的退出代码?

时间:2020-03-06 14:57:17  来源:igfitidea点击:

我在.NET中有一个简单的控制台应用程序。它只是大型应用程序的测试部分。我想指定控制台应用程序的"退出代码"。我该怎么做呢?

解决方案

int code = 2;
Environment.Exit( code );

System.Environment.ExitCode

http://msdn.microsoft.com/zh-CN/library/system.environment.exitcode.aspx

只需从main返回适当的代码即可。

int main(string[] args)
{
      return 0; //or exit code of your choice
}

3种选择:

  • 如果声明Main方法返回int,则可以从Main返回它。
  • 我们可以调用Environment.Exit(code)
  • 我们可以使用以下属性设置退出代码:Environment.ExitCode = -1;。如果没有其他设置返回代码或者使用上述其他选项之一的情况,则将使用此方法。

根据应用程序(控制台,服务,Web应用程序等),可以使用不同的方法。

如果主体具有无效的返回签名,请使用ExitCode,否则,我们需要通过返回的值对其进行"设置"。

Environment.ExitCode属性

If the Main method returns void, you can use this property to set the exit code that will be returned to the calling environment. If Main does not return void, this property is ignored. The initial value of this property is zero.

除了涵盖return int的答案外,还呼吁人们保持理智。请在枚举中定义退出代码,并在适当的地方加上Flags。它使调试和维护变得非常容易(而且,此外,我们可以在帮助屏幕上轻松打印出退出代码,我们确实拥有其中之一,对吗?)。

enum ExitCode : int {
  Success = 0,
  InvalidLogin = 1,
  InvalidFilename = 2,
  UnknownError = 10
}

int Main(string[] args) {
   return (int)ExitCode.Success;
}