Environment.ExitCode Propiedad

Definición

Obtiene o establece el código de salida del proceso.

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

Valor de propiedad

Int32

Un entero de 32 bits con signo que contiene el código de salida. El valor predeterminado es 0 (cero), lo que indica que el proceso se completó correctamente.

Ejemplos

A continuación se muestra una aplicación sencilla denominada Double.exe que duplica un valor entero que se le pasa como argumento de línea de comandos. El valor asigna códigos de error a la ExitCode propiedad para indicar condiciones de error. Tenga en cuenta que debe agregar una referencia al ensamblado System.Numerics.dll para compilar correctamente el ejemplo.

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;
      }
   }
}
open System
open System.Numerics

let ERROR_BAD_ARGUMENTS = 0xA0
let ERROR_ARITHMETIC_OVERFLOW = 0x216
let ERROR_INVALID_COMMAND_LINE = 0x667

let args = Environment.GetCommandLineArgs()
if args.Length = 1 then
    Environment.ExitCode <- ERROR_INVALID_COMMAND_LINE
else
    match BigInteger.TryParse args[1] with
    | true, value ->
        if value <= bigint Int32.MinValue || value >= bigint Int32.MaxValue then
            Environment.ExitCode <- ERROR_ARITHMETIC_OVERFLOW
        else
            printfn $"Result: {value * 2I}"
    | _ ->
        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

A continuación, se puede invocar el ejemplo desde un archivo por lotes como el siguiente, lo que hace que sus códigos de error sean accesibles mediante el ERRORLEVEL comando .

@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

A continuación se muestra una salida de ejemplo generada mediante la invocación del archivo por lotes.

>getdouble 123
Result: 246
Completed Successfully

>getdouble 5912323109093
Arithmetic overflow

>getdouble
Missing argument

>getdouble "a string"
Invalid argument

Tenga en cuenta que el código de Double.exe es idéntico en función al ejemplo siguiente, salvo que el anterior define un punto de entrada denominado Main que no tiene ningún valor devuelto, mientras que en este ejemplo se define un punto de entrada denominado Main que devuelve un entero.

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;
   }
}
open System
open System.Numerics

let ERROR_SUCCESS = 0
let ERROR_BAD_ARGUMENTS = 0xA0
let ERROR_ARITHMETIC_OVERFLOW = 0x216
let ERROR_INVALID_COMMAND_LINE = 0x667

[<EntryPoint>]
let main _ =
    let args = Environment.GetCommandLineArgs()
    if args.Length = 1 then
        ERROR_INVALID_COMMAND_LINE
    else
        match BigInteger.TryParse args[1] with
        | true, value ->
            if value <= bigint Int32.MinValue || value >= bigint Int32.MaxValue then
                ERROR_ARITHMETIC_OVERFLOW
            else
                printfn $"Result: {value * 2I}"
                ERROR_SUCCESS
        | _ ->
            ERROR_BAD_ARGUMENTS
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

Comentarios

Si el Main método devuelve void, puede usar esta propiedad para establecer el código de salida que se devolverá al entorno de llamada. Si Main no devuelve void, esta propiedad se omite. El valor inicial de esta propiedad es cero.

Advertencia

La ExitCode propiedad es un entero de 32 bits con signo. Para evitar que la propiedad devuelva un código de salida negativo, no debe usar valores mayores o iguales que 0x80000000.

Use un número distinto de cero para indicar un error. En la aplicación, puede definir sus propios códigos de error en una enumeración y devolver el código de error adecuado en función del escenario. Por ejemplo, devuelve un valor de 1 para indicar que el archivo necesario no está presente y un valor de 2 para indicar que el archivo tiene un formato incorrecto. Para obtener una lista de los códigos de salida usados por el sistema operativo Windows, consulte Códigos de error del sistema en la documentación de Windows.

Se aplica a