我在. net中有一个简单的控制台应用程序。这只是一个更大应用程序的测试部分。我想指定控制台应用程序的“退出代码”。我怎么做呢?
当前回答
换一种说法:
public static class ApplicationExitCodes
{
public static readonly int Failure = 1;
public static readonly int Success = 0;
}
其他回答
使用这段代码
Environment.Exit(0);
如果你不想返回任何东西,就使用0作为int。
枚举选项非常棒。但是,可以通过将数字相乘来改进:
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组成,等等。
只需从main返回相应的代码。
int Main(string[] args)
{
return 0; // Or exit code of your choice
}
有三种方法可用于从控制台应用程序返回退出代码。
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将允许您返回代码的组合。
此外,确保您的应用程序被编译为“控制台应用程序”。
作为斯科特·门罗回答的更新:
在c# 6.0和VB中。NET 14.0 (Visual Studio 2015),或环境。ExitCode或Environment.Exit(ExitCode)用于从控制台应用程序返回非零代码。改变Main的返回类型没有效果。 在f# 4.0 (Visual Studio 2015)中,主入口点的返回值被尊重。
推荐文章
- 为什么我不能在c#中有抽象静态方法?
- Nuget连接尝试失败“无法为源加载服务索引”
- net HttpClient。如何POST字符串值?
- 我如何使一个方法的返回类型泛型?
- 何时处理CancellationTokenSource?
- 如何获取正在执行的程序集版本?
- AutoMapper vs valueinjector
- 为什么控制台不。Writeline,控制台。在Visual Studio Express中编写工作?
- 什么是.NET程序集?
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- 函数应该返回空对象还是空对象?
- 如何转换日期时间?将日期时间
- 如何在c#中连接列表?
- 在c#中引用类型变量的“ref”的用途是什么?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作