我在. net中有一个简单的控制台应用程序。这只是一个更大应用程序的测试部分。我想指定控制台应用程序的“退出代码”。我怎么做呢?
当前回答
除了包含返回int的答案之外…这是对理智的恳求。请,请在枚举中定义您的退出代码,如果合适的话,请标记。它使调试和维护变得更加容易(而且,作为奖励,您可以轻松地在帮助屏幕上打印出退出代码——您确实有一个退出代码,对吧?)
enum ExitCode : int {
Success = 0,
InvalidLogin = 1,
InvalidFilename = 2,
UnknownError = 10
}
int Main(string[] args) {
return (int)ExitCode.Success;
}
其他回答
我这样做:
int exitCode = 0;
Environment.Exit(exitCode);
或者你可以抛出一个错误(个人偏好):
throw new ArgumentException("Code 0, Environment Exit");
我选择了ArgumentException,但你可以输入other。它会工作得很好。
int code = 2;
Environment.Exit( code );
有三种方法可用于从控制台应用程序返回退出代码。
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将允许您返回代码的组合。
此外,确保您的应用程序被编译为“控制台应用程序”。
枚举选项非常棒。但是,可以通过将数字相乘来改进:
enum ExitCodes : int
{
Success = 0,
SignToolNotInPath = 1,
AssemblyDirectoryBad = 2,
PFXFilePathBad = 4,
PasswordMissing = 8,
SignFailed = 16,
UnknownError = 32
}
在出现多个错误的情况下,将特定的错误数字加在一起将得到一个表示检测到的错误组合的唯一数字。
例如,错误级别6只能由错误4和错误2组成,12只能由错误4和错误8组成,14只能由错误2、错误4和错误8组成,等等。
除了包含返回int的答案之外…这是对理智的恳求。请,请在枚举中定义您的退出代码,如果合适的话,请标记。它使调试和维护变得更加容易(而且,作为奖励,您可以轻松地在帮助屏幕上打印出退出代码——您确实有一个退出代码,对吧?)
enum ExitCode : int {
Success = 0,
InvalidLogin = 1,
InvalidFilename = 2,
UnknownError = 10
}
int Main(string[] args) {
return (int)ExitCode.Success;
}
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何在iis7应用程序池中设置。net Framework 4.5版本