Environment.ExitCode Свойство
Определение
Возвращает или задает код выхода из процесса.Gets or sets the exit code of the process.
public:
static property int ExitCode { int get(); void set(int value); };
public static int ExitCode { get; set; }
member this.ExitCode : int with get, set
Public Shared Property ExitCode As Integer
Значение свойства
32-битовое целое число со знаком, содержащее код выхода.A 32-bit signed integer containing the exit code. Значение по умолчанию 0 (нуль), что соответствует успешно выполненному процессу.The default value is 0 (zero), which indicates that the process completed successfully.
Примеры
Ниже приведено простое приложение с именем Double.exe, которое удваивает целочисленное значение, передаваемое в качестве аргумента командной строки.The following is a simple app named Double.exe that doubles an integer value passed to it as a command-line argument. Значение присваивает коды ошибок ExitCode свойству, чтобы указать условия ошибки.The value assigns error codes to the ExitCode property to indicate error conditions. Обратите внимание, что для успешной компиляции примера необходимо добавить ссылку на сборку System.Numerics.dll.Note that you must add a reference to the System.Numerics.dll assembly to successfully compile the example.
using System;
using System.Numerics;
public class Example
{
private const int ERROR_BAD_ARGUMENTS = 0xA0;
private const int ERROR_ARITHMETIC_OVERFLOW = 0x216;
private const int ERROR_INVALID_COMMAND_LINE = 0x667;
public static void Main()
{
string[] args = Environment.GetCommandLineArgs();
if (args.Length == 1) {
Environment.ExitCode = ERROR_INVALID_COMMAND_LINE;
}
else {
BigInteger value = 0;
if (BigInteger.TryParse(args[1], out value))
if (value <= Int32.MinValue || value >= Int32.MaxValue)
Environment.ExitCode = ERROR_ARITHMETIC_OVERFLOW;
else
Console.WriteLine("Result: {0}", value * 2);
else
Environment.ExitCode = ERROR_BAD_ARGUMENTS;
}
}
}
Imports System.Numerics
Module Example
Private Const ERROR_BAD_ARGUMENTS As Integer = &hA0
Private Const ERROR_ARITHMETIC_OVERFLOW As Integer = &h216
Private Const ERROR_INVALID_COMMAND_LINE As Integer = &h667
Public Sub Main()
Dim args() As String = Environment.GetCommandLineArgs()
If args.Length = 1 Then
Environment.ExitCode = ERROR_INVALID_COMMAND_LINE
Else
Dim value As BigInteger = 0
If BigInteger.TryParse(args(1), value) Then
If value <= Int32.MinValue Or value >= Int32.MaxValue
Environment.ExitCode = ERROR_ARITHMETIC_OVERFLOW
Else
Console.WriteLine("Result: {0}", value * 2)
End If
Else
Environment.ExitCode = ERROR_BAD_ARGUMENTS
End If
End If
End Sub
End Module
Затем этот пример можно вызвать из пакетного файла, например следующего, который делает коды ошибок доступными с помощью ERRORLEVEL
команды.The example can then be invoked from a batch file such as the following, which makes its error codes accessible by using the ERRORLEVEL
command.
echo off
Double.exe %1
If errorlevel 1639 goto NoArg
if errorlevel 534 goto Overflow
if errorlevel 160 goto BadArg
if errorlevel 0 echo Completed Successfully
goto :EOF
:NoArg
echo Missing argument
goto :EOF
: Overflow
echo Arithmetic overflow
goto :EOF
:BadArg
echo Invalid argument
goto :EOF
Ниже приведен пример выходных данных, полученных при вызове пакетного файла.The following shows some sample output produced by invoking the batch file.
>getdouble 123>echo offResult: 246Completed Successfully>getdouble 5912323109093>echo offArithmetic overflow>getdouble>echo offMissing argument>getdouble "a string">echo offInvalid argument
Обратите внимание, что код для Double.exe идентичен в приведенном ниже примере, за исключением того, что первый определяет точку входа с именем Main
, не имеющую возвращаемого значения, тогда как в этом примере определяется точка входа с именем Main
, которая возвращает целое число.Note that code for Double.exe is identical in function to the following example, except that the former defines an entry point named Main
that has no return value, whereas this example defines an entry point named Main
that returns an integer.
using System;
using System.Numerics;
public class Example
{
private const int ERROR_SUCCESS = 0;
private const int ERROR_BAD_ARGUMENTS = 0xA0;
private const int ERROR_ARITHMETIC_OVERFLOW = 0x216;
private const int ERROR_INVALID_COMMAND_LINE = 0x667;
public static int Main()
{
string[] args = Environment.GetCommandLineArgs();
if (args.Length == 1) {
return ERROR_INVALID_COMMAND_LINE;
}
else {
BigInteger value = 0;
if (BigInteger.TryParse(args[1], out value))
if (value <= Int32.MinValue || value >= Int32.MaxValue)
return ERROR_ARITHMETIC_OVERFLOW;
else
Console.WriteLine("Result: {0}", value * 2);
else
return ERROR_BAD_ARGUMENTS;
}
return ERROR_SUCCESS;
}
}
Imports System.Numerics
Module Example
Private Const ERROR_SUCCESS As Integer = 0
Private Const ERROR_BAD_ARGUMENTS As Integer = &hA0
Private Const ERROR_ARITHMETIC_OVERFLOW As Integer = &h216
Private Const ERROR_INVALID_COMMAND_LINE As Integer = &h667
Public Function Main() As Integer
Dim args() As String = Environment.GetCommandLineArgs()
If args.Length = 1 Then
Return ERROR_INVALID_COMMAND_LINE
Else
Dim value As BigInteger = 0
If BigInteger.TryParse(args(1), value) Then
If value <= Int32.MinValue Or value >= Int32.MaxValue
Return ERROR_ARITHMETIC_OVERFLOW
Else
Console.WriteLine("Result: {0}", value * 2)
End If
Else
Return ERROR_BAD_ARGUMENTS
End If
End If
Return ERROR_SUCCESS
End Function
End Module
Комментарии
Если Main
метод возвращает значение void
, можно использовать это свойство, чтобы задать код выхода, который будет возвращен в вызывающую среду.If the Main
method returns void
, you can use this property to set the exit code that will be returned to the calling environment. Если не Main
возвращает void
значение, это свойство игнорируется.If Main
does not return void
, this property is ignored. Начальное значение этого свойства равно нулю.The initial value of this property is zero.
Предупреждение
ExitCodeСвойство представляет собой 32-разрядное целое число со знаком.The ExitCode property is a signed 32-bit integer. Чтобы свойство не возвращало отрицательного кода выхода, не следует использовать значения, превышающие или равные 0x80000000.To prevent the property from returning a negative exit code, you should not use values greater than or equal to 0x80000000.
Чтобы указать ошибку, используйте ненулевое число.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. Например, верните значение 1, чтобы указать, что необходимый файл отсутствует, и значение 2, чтобы указать, что файл имеет неправильный формат.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. Список кодов выхода, используемых операционной системой Windows, см. в разделе коды системных ошибок в документации Windows.For a list of exit codes used by the Windows operating system, see System Error Codes in the Windows documentation.