我在. net中有一个简单的控制台应用程序。这只是一个更大应用程序的测试部分。我想指定控制台应用程序的“退出代码”。我怎么做呢?


当前回答

有三种方法可用于从控制台应用程序返回退出代码。

Modify the Main method in your application so that it returns an int instead of void (a function that returns an Integer instead of Sub in VB.NET) and then return the exit code from that method. Set the Environment.ExitCode property to the exit code. Note that method 1. takes precedence - if the Main method returns anything other than void (is a Sub in VB.Net) then the value of this property will be ignored. Pass the exit code to the Environment.Exit method. This will terminate the process immediately as opposed to the other two methods.

应该遵守的一个重要标准是,0代表“成功”。

在相关主题中,考虑使用枚举定义应用程序将返回的退出代码。FlagsAttribute将允许您返回代码的组合。

此外,确保您的应用程序被编译为“控制台应用程序”。

其他回答

我这样做:

int exitCode = 0;
Environment.Exit(exitCode);

或者你可以抛出一个错误(个人偏好):

throw new ArgumentException("Code 0, Environment Exit");

我选择了ArgumentException,但你可以输入other。它会工作得很好。

除了包含返回int的答案之外…这是对理智的恳求。请,请在枚举中定义您的退出代码,如果合适的话,请标记。它使调试和维护变得更加容易(而且,作为奖励,您可以轻松地在帮助屏幕上打印出退出代码——您确实有一个退出代码,对吧?)

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

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

三个选项:

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

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

只需从main返回相应的代码。

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

如果你的main有一个无效返回签名,请使用ExitCode。否则,您需要通过您返回的值“设置”它。

从环境。ExitCode属性:

如果Main方法返回void,则可以使用此属性设置将返回到调用环境的退出代码。如果Main不返回void,则忽略此属性。这个属性的初始值为零。