Int32.TryParse Método

Definição

Converte a representação de cadeia de caracteres de um número no inteiro com sinal de 32 bits equivalente. Um valor retornado indica se a operação foi bem-sucedida.

Sobrecargas

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int32)

Tenta analisar um intervalo de caracteres UTF-8 em um valor.

TryParse(ReadOnlySpan<Char>, Int32)

Converte a representação de intervalo de um número em um formato específico da cultura e um estilo especificados em seu equivalente de inteiro com sinal de 32 bits. Um valor retornado indica se a conversão foi bem-sucedida.

TryParse(String, Int32)

Converte a representação de cadeia de caracteres de um número no inteiro com sinal de 32 bits equivalente. Um valor retornado indica se a conversão foi bem-sucedida.

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int32)

Tenta analisar um intervalo de caracteres em um valor.

TryParse(String, IFormatProvider, Int32)

Tenta analisar uma cadeia de caracteres em um valor.

TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Int32)

Tenta analisar um intervalo de caracteres UTF-8 em um valor.

TryParse(ReadOnlySpan<Byte>, Int32)

Tenta converter um intervalo de caracteres UTF-8 que contém a representação de cadeia de caracteres de um número em seu inteiro com sinal de 32 bits equivalente.

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Int32)

Converte a representação de intervalo de um número em um formato específico da cultura e um estilo especificados em seu equivalente de inteiro com sinal de 32 bits. Um valor retornado indica se a conversão foi bem-sucedida.

TryParse(String, NumberStyles, IFormatProvider, Int32)

Converte a representação de cadeia de caracteres de um número em um estilo e formato específico da cultura especificados em seu equivalente de inteiro com sinal de 32 bits. Um valor retornado indica se a conversão foi bem-sucedida.

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int32)

Origem:
Int32.cs
Origem:
Int32.cs

Tenta analisar um intervalo de caracteres UTF-8 em um valor.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = IUtf8SpanParsable<int>::TryParse;
public static bool TryParse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider, out int result);
static member TryParse : ReadOnlySpan<byte> * IFormatProvider * int -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider, ByRef result As Integer) As Boolean

Parâmetros

utf8Text
ReadOnlySpan<Byte>

O intervalo de caracteres UTF-8 a serem analisados.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas à cultura sobre utf8Text.

result
Int32

No retorno, contém o resultado da análise utf8Text com êxito ou de um valor indefinido em caso de falha.

Retornos

true se utf8Text tiver sido analisado com êxito; caso contrário, false.

Aplica-se a

TryParse(ReadOnlySpan<Char>, Int32)

Origem:
Int32.cs
Origem:
Int32.cs
Origem:
Int32.cs

Converte a representação de intervalo de um número em um formato específico da cultura e um estilo especificados em seu equivalente de inteiro com sinal de 32 bits. Um valor retornado indica se a conversão foi bem-sucedida.

public:
 static bool TryParse(ReadOnlySpan<char> s, [Runtime::InteropServices::Out] int % result);
public static bool TryParse (ReadOnlySpan<char> s, out int result);
static member TryParse : ReadOnlySpan<char> * int -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), ByRef result As Integer) As Boolean

Parâmetros

s
ReadOnlySpan<Char>

Um intervalo que contém os caracteres que representam o número a ser convertido.

result
Int32

Quando esse método retornar, conterá o equivalente do valor inteiro com sinal de 32 bits do número contido em s, se a conversão tiver sido bem-sucedida, ou zero, se a conversão tiver falhado. A conversão falhará se o s parâmetro for null ou Empty, não estiver em um formato compatível com styleou representar um número menor que Int32.MinValue ou maior que Int32.MaxValue. Este parâmetro é passado não inicializado; qualquer valor fornecido originalmente em result será substituído.

Retornos

true caso s tenha sido convertido com êxito; do contrário, false.

Aplica-se a

TryParse(String, Int32)

Origem:
Int32.cs
Origem:
Int32.cs
Origem:
Int32.cs

Converte a representação de cadeia de caracteres de um número no inteiro com sinal de 32 bits equivalente. Um valor retornado indica se a conversão foi bem-sucedida.

public:
 static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] int % result);
public static bool TryParse (string s, out int result);
public static bool TryParse (string? s, out int result);
static member TryParse : string * int -> bool
Public Shared Function TryParse (s As String, ByRef result As Integer) As Boolean

Parâmetros

s
String

Uma cadeia de caracteres que contém um número a ser convertido.

result
Int32

Quando esse método retornar, conterá o equivalente do valor inteiro com sinal de 32 bits do número contido em s, se a conversão tiver sido bem-sucedida, ou zero, se a conversão tiver falhado. A conversão falhará se o s parâmetro for null ou Empty, não for do formato correto ou representar um número menor que Int32.MinValue ou maior que Int32.MaxValue. Este parâmetro é passado não inicializado; qualquer valor fornecido originalmente em result será substituído.

Retornos

true caso s tenha sido convertido com êxito; do contrário, false.

Exemplos

O exemplo a seguir chama o Int32.TryParse(String, Int32) método com vários valores de cadeia de caracteres diferentes.

using namespace System;


   void TryToParse(String^ value)
   {
      Int32 number;
      bool result = Int32::TryParse(value, number);
      if (result) {
         Console::WriteLine("Converted '{0}' to {1}.", value, number);
      }
      else {
         if (value == nullptr) value = "";
         Console::WriteLine("Attempted conversion of '{0}' failed.", value);
      }
   }


void main()
{
      TryToParse(nullptr);
      TryToParse("160519");
      TryToParse("9432.0");
      TryToParse("16,667");
      TryToParse("   -322   ");
      TryToParse("+4302");
      TryToParse("(100);");
      TryToParse("01FA");
}
// The example displays the following output:
//      Attempted conversion of '' failed.
//      Converted '160519' to 160519.
//      Attempted conversion of '9432.0' failed.
//      Attempted conversion of '16,667' failed.
//      Converted '   -322   ' to -322.
//      Converted '+4302' to 4302.
//      Attempted conversion of '(100);' failed.
//      Attempted conversion of '01FA' failed.
using System;

public class Example
{
   public static void Main()
   {
      string[] values = { null, "160519", "9432.0", "16,667",
                          "   -322   ", "+4302", "(100);", "01FA" };
      foreach (var value in values)
      {
         int number;

         bool success = int.TryParse(value, out number);
         if (success)
         {
            Console.WriteLine($"Converted '{value}' to {number}.");
         }
         else
         {
            Console.WriteLine($"Attempted conversion of '{value ?? "<null>"}' failed.");
         }
      }
   }
}
// The example displays the following output:
//       Attempted conversion of '<null>' failed.
//       Converted '160519' to 160519.
//       Attempted conversion of '9432.0' failed.
//       Attempted conversion of '16,667' failed.
//       Converted '   -322   ' to -322.
//       Converted '+4302' to 4302.
//       Attempted conversion of '(100);' failed.
//       Attempted conversion of '01FA' failed.
open System

let values = 
   [ null; "160519"; "9432.0"; "16,667"
     "   -322   "; "+4302"; "(100);"; "01FA" ]
for value in values do
    match Int32.TryParse value with
    | true, number -> 
        printfn $"Converted '{value}' to {number}."
    | _ -> 
        printfn $"""Attempted conversion of '{if isNull value then "<null>" else value}' failed."""
         
// The example displays the following output:
//       Attempted conversion of '<null>' failed.
//       Converted '160519' to 160519.
//       Attempted conversion of '9432.0' failed.
//       Attempted conversion of '16,667' failed.
//       Converted '   -322   ' to -322.
//       Converted '+4302' to 4302.
//       Attempted conversion of '(100);' failed.
//       Attempted conversion of '01FA' failed.
Module Example
   Public Sub Main()
      Dim values() As String = { Nothing, "160519", "9432.0", "16,667",
                                 "   -322   ", "+4302", "(100);", 
                                 "01FA" }

      For Each value In values
         Dim number As Integer
    
         Dim success As Boolean = Int32.TryParse(value, number)
         If success Then
            Console.WriteLine("Converted '{0}' to {1}.", value, number)
         Else
            Console.WriteLine("Attempted conversion of '{0}' failed.", 
                              If(value ,"<null>"))
         End If     
      Next
   End Sub
End Module
' The example displays the following output to the console:
'       Attempted conversion of '<null>' failed.
'       Converted '160519' to 160519.
'       Attempted conversion of '9432.0' failed.
'       Attempted conversion of '16,667' failed.
'       Converted '   -322   ' to -322.
'       Converted '+4302' to 4302.
'       Attempted conversion of '(100)' failed.
'       Attempted conversion of '01FA' failed.

Algumas das cadeias de caracteres que o TryParse(String, Int32) método não consegue converter neste exemplo são:

  • "9432.0". A conversão falha porque a cadeia de caracteres não pode conter um separador decimal; ele deve conter apenas dígitos integrais.

  • "16,667". A conversão falha porque a cadeia de caracteres não pode conter separadores de grupo; ele deve conter apenas dígitos integrais.

  • "(100)". A conversão falha porque a cadeia de caracteres não pode conter um sinal negativo diferente do definido pelas propriedades e NumberFormatInfo.NumberNegativePattern da NumberFormatInfo.NegativeSign cultura atual.

  • "01FA". A conversão falha porque a cadeia de caracteres não pode conter dígitos hexadecimal; ele deve conter apenas dígitos decimais.

Comentários

O TryParse método é semelhante ao Parse método , exceto que o TryParse método não gera uma exceção se a conversão falhar. Ele elimina a necessidade de usar a identificação de exceções para testar um FormatException caso esse s seja inválido e não possa ser analisado com êxito.

O parâmetro s contém um número da forma:

[ws][sign]digits[ws]

Itens entre colchetes ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.

Elemento Descrição
ws Espaço em branco opcional.
sign Um sinal opcional.
dígitos Uma sequência de dígitos que varia de 0 a 9.

O parâmetro s é interpretado usando-se o estilo NumberStyles.Integer. Além dos dígitos decimais, somente espaços à esquerda e à direita, juntamente com um sinal à esquerda, são permitidos. Para definir explicitamente os elementos de estilo junto com as informações de formatação específicas da cultura que podem estar presentes no s, use o Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) método .

O parâmetro s é analisado usando-se as informações de formatação em um objeto NumberFormatInfo inicializado para a cultura do sistema atual. Para obter mais informações, consulte CurrentInfo.

Essa sobrecarga do TryParse método interpreta todos os dígitos no s parâmetro como dígitos decimais. Para analisar a representação de cadeia de caracteres de um número hexadecimal, chame a Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) sobrecarga.

Confira também

Aplica-se a

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int32)

Origem:
Int32.cs
Origem:
Int32.cs
Origem:
Int32.cs

Tenta analisar um intervalo de caracteres em um valor.

public:
 static bool TryParse(ReadOnlySpan<char> s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = ISpanParsable<int>::TryParse;
public static bool TryParse (ReadOnlySpan<char> s, IFormatProvider? provider, out int result);
static member TryParse : ReadOnlySpan<char> * IFormatProvider * int -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), provider As IFormatProvider, ByRef result As Integer) As Boolean

Parâmetros

s
ReadOnlySpan<Char>

O intervalo de caracteres a serem analisados.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas à cultura sobre s.

result
Int32

Quando esse método retorna, contém o resultado da análise scom êxito ou um valor indefinido sobre a falha.

Retornos

true se s tiver sido analisado com êxito; caso contrário, false.

Aplica-se a

TryParse(String, IFormatProvider, Int32)

Origem:
Int32.cs
Origem:
Int32.cs
Origem:
Int32.cs

Tenta analisar uma cadeia de caracteres em um valor.

public:
 static bool TryParse(System::String ^ s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = IParsable<int>::TryParse;
public static bool TryParse (string? s, IFormatProvider? provider, out int result);
static member TryParse : string * IFormatProvider * int -> bool
Public Shared Function TryParse (s As String, provider As IFormatProvider, ByRef result As Integer) As Boolean

Parâmetros

s
String

A cadeia de caracteres a ser analisada.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas à cultura sobre s.

result
Int32

Quando esse método retorna, contém o resultado da análise s com êxito ou um valor indefinido em caso de falha.

Retornos

true se s tiver sido analisado com êxito; caso contrário, false.

Aplica-se a

TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Int32)

Origem:
Int32.cs
Origem:
Int32.cs

Tenta analisar um intervalo de caracteres UTF-8 em um valor.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = System::Numerics::INumberBase<int>::TryParse;
public static bool TryParse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style, IFormatProvider? provider, out int result);
static member TryParse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider * int -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), style As NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean

Parâmetros

utf8Text
ReadOnlySpan<Byte>

O intervalo de caracteres UTF-8 a serem analisados.

style
NumberStyles

Uma combinação bit a bit de estilos numéricos que podem estar presentes em utf8Text.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas à cultura sobre utf8Text.

result
Int32

No retorno, contém o resultado da análise utf8Text com êxito ou de um valor indefinido em caso de falha.

Retornos

true se utf8Text tiver sido analisado com êxito; caso contrário, false.

Aplica-se a

TryParse(ReadOnlySpan<Byte>, Int32)

Origem:
Int32.cs
Origem:
Int32.cs

Tenta converter um intervalo de caracteres UTF-8 que contém a representação de cadeia de caracteres de um número em seu inteiro com sinal de 32 bits equivalente.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, [Runtime::InteropServices::Out] int % result);
public static bool TryParse (ReadOnlySpan<byte> utf8Text, out int result);
static member TryParse : ReadOnlySpan<byte> * int -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), ByRef result As Integer) As Boolean

Parâmetros

utf8Text
ReadOnlySpan<Byte>

Um intervalo que contém os caracteres UTF-8 que representam o número a ser convertido.

result
Int32

Quando esse método retorna, contém o valor inteiro com sinal de 32 bits equivalente ao número contido em utf8Text se a conversão foi bem-sucedida ou zero se a conversão falhou. Este parâmetro é passado não inicializado; qualquer valor fornecido originalmente no resultado será substituído.

Retornos

true caso utf8Text tenha sido convertido com êxito; do contrário, false.

Aplica-se a

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Int32)

Origem:
Int32.cs
Origem:
Int32.cs
Origem:
Int32.cs

Converte a representação de intervalo de um número em um formato específico da cultura e um estilo especificados em seu equivalente de inteiro com sinal de 32 bits. Um valor retornado indica se a conversão foi bem-sucedida.

public:
 static bool TryParse(ReadOnlySpan<char> s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result);
public:
 static bool TryParse(ReadOnlySpan<char> s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = System::Numerics::INumberBase<int>::TryParse;
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider? provider, out int result);
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider provider, out int result);
static member TryParse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider * int -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), style As NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean

Parâmetros

s
ReadOnlySpan<Char>

Um intervalo que contém os caracteres que representam o número a ser convertido. O intervalo é interpretado usando o estilo especificado por style.

style
NumberStyles

Um combinação bit a bit de valores de enumeração que indica os elementos de estilo que podem estar presentes em s. Um valor típico a ser especificado é Integer.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura sobre s.

result
Int32

Quando esse método retornar, conterá o equivalente do valor inteiro com sinal de 32 bits do número contido em s, se a conversão tiver sido bem-sucedida, ou zero, se a conversão tiver falhado. A conversão falhará se o s parâmetro for null ou Empty, não estiver em um formato compatível com styleou representar um número menor que Int32.MinValue ou maior que Int32.MaxValue. Este parâmetro é passado não inicializado; qualquer valor fornecido originalmente em result será substituído.

Retornos

true caso s tenha sido convertido com êxito; do contrário, false.

Aplica-se a

TryParse(String, NumberStyles, IFormatProvider, Int32)

Origem:
Int32.cs
Origem:
Int32.cs
Origem:
Int32.cs

Converte a representação de cadeia de caracteres de um número em um estilo e formato específico da cultura especificados em seu equivalente de inteiro com sinal de 32 bits. Um valor retornado indica se a conversão foi bem-sucedida.

public:
 static bool TryParse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result);
public:
 static bool TryParse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = System::Numerics::INumberBase<int>::TryParse;
public static bool TryParse (string s, System.Globalization.NumberStyles style, IFormatProvider provider, out int result);
public static bool TryParse (string? s, System.Globalization.NumberStyles style, IFormatProvider? provider, out int result);
static member TryParse : string * System.Globalization.NumberStyles * IFormatProvider * int -> bool
Public Shared Function TryParse (s As String, style As NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean

Parâmetros

s
String

Uma cadeia de caracteres que contém um número a ser convertido. A cadeia de caracteres é interpretada usando o estilo especificado por style.

style
NumberStyles

Um combinação bit a bit de valores de enumeração que indica os elementos de estilo que podem estar presentes em s. Um valor típico a ser especificado é Integer.

provider
IFormatProvider

Um objeto que fornece informações de formatação específicas da cultura sobre s.

result
Int32

Quando esse método retornar, conterá o equivalente do valor inteiro com sinal de 32 bits do número contido em s, se a conversão tiver sido bem-sucedida, ou zero, se a conversão tiver falhado. A conversão falhará se o s parâmetro for null ou Empty, não estiver em um formato compatível com styleou representar um número menor que Int32.MinValue ou maior que Int32.MaxValue. Este parâmetro é passado não inicializado; qualquer valor fornecido originalmente em result será substituído.

Retornos

true caso s tenha sido convertido com êxito; do contrário, false.

Exceções

style não é um valor NumberStyles.

- ou -

style não é uma combinação de valores AllowHexSpecifier e HexNumber.

Exemplos

O exemplo a seguir chama o Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) método com várias cadeias de caracteres e NumberStyles valores diferentes.

using namespace System;
using namespace System::Globalization;

void CallTryParse(String^ stringToConvert, NumberStyles styles)
{
      Int32 number;
      CultureInfo^ provider;

      // If currency symbol is allowed, use en-US culture. 
      if (((Int32) (styles & NumberStyles::AllowCurrencySymbol)) > 0)
         provider = gcnew CultureInfo("en-US");
      else
         provider = CultureInfo::InvariantCulture;

      bool result = Int32::TryParse(stringToConvert, styles, 
                                   provider, number);
      if (result)
         Console::WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
      else
         Console::WriteLine("Attempted conversion of '{0}' failed.", 
                           Convert::ToString(stringToConvert));
}

void main()
{
      String^ numericString;
      NumberStyles styles;

      numericString = "106779";
      styles = NumberStyles::Integer;
      CallTryParse(numericString, styles);

      numericString = "-30677";
      styles = NumberStyles::None;
      CallTryParse(numericString, styles);

      styles = NumberStyles::AllowLeadingSign;
      CallTryParse(numericString, styles);

      numericString = "301677-";
      CallTryParse(numericString, styles);

      styles = styles | NumberStyles::AllowTrailingSign;
      CallTryParse(numericString, styles);

      numericString = "$10634";
      styles = NumberStyles::Integer;
      CallTryParse(numericString, styles);

      styles = NumberStyles::Integer | NumberStyles::AllowCurrencySymbol;
      CallTryParse(numericString, styles);

      numericString = "10345.00";
      styles = NumberStyles::Integer | NumberStyles::AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "10345.72";
      styles = NumberStyles::Integer | NumberStyles::AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "22,593"; 
      styles = NumberStyles::Integer | NumberStyles::AllowThousands;
      CallTryParse(numericString, styles);

      numericString = "12E-01";
      styles = NumberStyles::Integer | NumberStyles::AllowExponent;
      CallTryParse(numericString, styles); 

      numericString = "12E03";
      CallTryParse(numericString, styles); 

      numericString = "80c1";
      CallTryParse(numericString, NumberStyles::HexNumber);

      numericString = "0x80C1";
      CallTryParse(numericString, NumberStyles::HexNumber);      
      Console::ReadLine();
}
// The example displays the following output:
//      Converted '106779' to 106779.
//      Attempted conversion of '-30677' failed.
//      Converted '-30677' to -30677.
//      Attempted conversion of '301677-' failed.
//      Converted '301677-' to -301677.
//      Attempted conversion of '$10634' failed.
//      Converted '$10634' to 10634.
//      Converted '10345.00' to 10345.
//      Attempted conversion of '10345.72' failed.
//      Converted '22,593' to 22593.
//      Attempted conversion of '12E-01' failed.
//      Converted '12E03' to 12000.
//      Converted '80c1' to 32961.
//      Attempted conversion of '0x80C1' failed.
using System;
using System.Globalization;

public class StringParsing
{
   public static void Main()
   {
      string numericString;
      NumberStyles styles;

      numericString = "106779";
      styles = NumberStyles.Integer;
      CallTryParse(numericString, styles);

      numericString = "-30677";
      styles = NumberStyles.None;
      CallTryParse(numericString, styles);

      styles = NumberStyles.AllowLeadingSign;
      CallTryParse(numericString, styles);

      numericString = "301677-";
      CallTryParse(numericString, styles);

      styles = styles | NumberStyles.AllowTrailingSign;
      CallTryParse(numericString, styles);

      numericString = "$10634";
      styles = NumberStyles.Integer;
      CallTryParse(numericString, styles);

      styles = NumberStyles.Integer | NumberStyles.AllowCurrencySymbol;
      CallTryParse(numericString, styles);

      numericString = "10345.00";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "10345.72";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "22,593";
      styles = NumberStyles.Integer | NumberStyles.AllowThousands;
      CallTryParse(numericString, styles);

      numericString = "12E-01";
      styles = NumberStyles.Integer | NumberStyles.AllowExponent;
      CallTryParse(numericString, styles);

      numericString = "12E03";
      CallTryParse(numericString, styles);

      numericString = "80c1";
      CallTryParse(numericString, NumberStyles.HexNumber);

      numericString = "0x80C1";
      CallTryParse(numericString, NumberStyles.HexNumber);
   }

   private static void CallTryParse(string stringToConvert, NumberStyles styles)
   {
      CultureInfo provider;

      // If currency symbol is allowed, use en-US culture.
      if ((styles & NumberStyles.AllowCurrencySymbol) > 0)
         provider = new CultureInfo("en-US");
      else
         provider = CultureInfo.InvariantCulture;

      bool success = int.TryParse(stringToConvert, styles,
                                   provider, out int number);
      if (success)
         Console.WriteLine($"Converted '{stringToConvert}' to {number}.");
      else
         Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed.");
   }
}
// The example displays the following output to the console:
//       Converted '106779' to 106779.
//       Attempted conversion of '-30677' failed.
//       Converted '-30677' to -30677.
//       Attempted conversion of '301677-' failed.
//       Converted '301677-' to -301677.
//       Attempted conversion of '$10634' failed.
//       Converted '$10634' to 10634.
//       Converted '10345.00' to 10345.
//       Attempted conversion of '10345.72' failed.
//       Converted '22,593' to 22593.
//       Attempted conversion of '12E-01' failed.
//       Converted '12E03' to 12000.
//       Converted '80c1' to 32961.
//       Attempted conversion of '0x80C1' failed.
open System
open System.Globalization

let callTryParse (stringToConvert: string) styles =
    let provider =
        // If currency symbol is allowed, use en-US culture.
        if int (styles &&& NumberStyles.AllowCurrencySymbol) > 0 then
            CultureInfo "en-US"
        else
            CultureInfo.InvariantCulture

    match Int32.TryParse(stringToConvert, styles, provider) with
    | true, number ->
        printfn $"Converted '{stringToConvert}' to {number}."
    | _ ->
        printfn $"Attempted conversion of '{stringToConvert}' failed."

[<EntryPoint>]
let main _ =
    let numericString = "106779"
    let styles = NumberStyles.Integer
    callTryParse numericString styles

    let numericString = "-30677"
    let styles = NumberStyles.None
    callTryParse numericString styles

    let styles = NumberStyles.AllowLeadingSign
    callTryParse numericString styles

    let numericString = "301677-"
    callTryParse numericString styles

    let styles = styles ||| NumberStyles.AllowTrailingSign
    callTryParse numericString styles

    let numericString = "$10634"
    let styles = NumberStyles.Integer
    callTryParse numericString styles

    let styles = NumberStyles.Integer ||| NumberStyles.AllowCurrencySymbol
    callTryParse numericString styles

    let numericString = "10345.00"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint
    callTryParse numericString styles

    let numericString = "10345.72"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint
    callTryParse numericString styles

    let numericString = "22,593"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowThousands
    callTryParse numericString styles

    let numericString = "12E-01"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowExponent
    callTryParse numericString styles

    let numericString = "12E03"
    callTryParse numericString styles

    let numericString = "80c1"
    callTryParse numericString NumberStyles.HexNumber

    let numericString = "0x80C1"
    callTryParse numericString NumberStyles.HexNumber

    0

// The example displays the following output to the console:
//       Converted '106779' to 106779.
//       Attempted conversion of '-30677' failed.
//       Converted '-30677' to -30677.
//       Attempted conversion of '301677-' failed.
//       Converted '301677-' to -301677.
//       Attempted conversion of '$10634' failed.
//       Converted '$10634' to 10634.
//       Converted '10345.00' to 10345.
//       Attempted conversion of '10345.72' failed.
//       Converted '22,593' to 22593.
//       Attempted conversion of '12E-01' failed.
//       Converted '12E03' to 12000.
//       Converted '80c1' to 32961.
//       Attempted conversion of '0x80C1' failed.
Imports System.Globalization

Module StringParsing
   Public Sub Main()
      Dim numericString As String
      Dim styles As NumberStyles
      
      numericString = "106779"
      styles = NumberStyles.Integer
      CallTryParse(numericString, styles)
      
      numericString = "-30677"
      styles = NumberStyles.None
      CallTryParse(numericString, styles)
      
      styles = NumberStyles.AllowLeadingSign
      CallTryParse(numericString, styles)
      
      numericString = "301677-"
      CallTryParse(numericString, styles)
      
      styles = styles Or NumberStyles.AllowTrailingSign
      CallTryParse(numericString, styles)
      
      numericString = "$10634"
      styles = NumberStyles.Integer
      CallTryParse(numericString, styles)
      
      styles = NumberStyles.Integer Or NumberStyles.AllowCurrencySymbol
      CallTryParse(numericString, styles)

      numericString = "10345.00"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(numericString, styles)
      
      numericString = "10345.72"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(numericString, styles)

      numericString = "22,593" 
      styles = NumberStyles.Integer Or NumberStyles.AllowThousands
      CallTryParse(numericString, styles)
      
      numericString = "12E-01"
      styles = NumberStyles.Integer Or NumberStyles.AllowExponent
      CallTryParse(numericString, styles) 
          
      numericString = "12E03"
      CallTryParse(numericString, styles) 
      
      numericString = "80c1"
      CallTryParse(numericString, NumberStyles.HexNumber)
      
      numericString = "0x80C1"
      CallTryParse(numericString, NumberStyles.HexNumber)
   End Sub
   
   Private Sub CallTryParse(stringToConvert As String, styles AS NumberStyles)
      Dim number As Integer
      Dim provider As CultureInfo
      
      ' If currency symbol is allowed, use en-US culture.
      If CBool(styles And NumberStyles.AllowCurrencySymbol) Then
         provider = CultureInfo.CurrentCulture
      Else
         provider = New CultureInfo("en-US")
      End If
      
      Dim result As Boolean = Int32.TryParse(stringToConvert, styles, _
                                             provider, number)
      If result Then
         Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
      Else
         Console.WriteLine("Attempted conversion of '{0}' failed.", _
                           Convert.ToString(stringToConvert))
      End If                                                                           
   End Sub
End Module
' The example displays the following output to the console:
'       Converted '106779' to 106779.
'       Attempted conversion of '-30677' failed.
'       Converted '-30677' to -30677.
'       Attempted conversion of '301677-' failed.
'       Converted '301677-' to -301677.
'       Attempted conversion of '$10634' failed.
'       Converted '$10634' to 10634.
'       Converted '10345.00' to 10345.
'       Attempted conversion of '10345.72' failed.
'       Converted '22,593' to 22593.
'       Attempted conversion of '12E-01' failed.
'       Converted '12E03' to 12000.
'       Converted '80c1' to 32961.
'       Attempted conversion of '0x80C1' failed.

Comentários

O TryParse método é semelhante ao Parse método , exceto que o TryParse método não gera uma exceção se a conversão falhar. Elimina a necessidade de usar o tratamento de exceção para testar um FormatException caso s seja inválido e não possa ser analisado com êxito.

O parâmetro style define os elementos de estilo (como o espaço em branco ou um sinal positivo ou negativo) que são permitidos no parâmetro s para que a operação de análise seja bem-sucedida. Ele deve ser uma combinação de sinalizadores de bits da enumeração NumberStyles. Dependendo do valor de style, o parâmetro s pode incluir os seguintes elementos:

[ws][$][sign][digits,]digits[.fractional_digits][e[sign]digits][ws]

Ou, se o style parâmetro incluir AllowHexSpecifier:

[ws]hexdigits[ws]

Itens entre colchetes ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.

Elemento Descrição
ws Espaço em branco opcional. O espaço em branco pode ser exibido no início de s caso style inclua o sinalizador NumberStyles.AllowLeadingWhite ou no final de s caso style inclua o sinalizador NumberStyles.AllowTrailingWhite.
$ Um símbolo de moeda específico de cultura. A posição na cadeia de caracteres é definida pela propriedade CurrencyPositivePattern do objeto NumberFormatInfo retornado pelo método GetFormat do parâmetro provider. O símbolo de moeda pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowCurrencySymbol.
sign Um sinal opcional. Um símbolo de sinal poderá aparecer se sstyle incluir os NumberStyles.AllowLeadingSign sinalizadores ou NumberStyles.AllowTrailingSign .
dígitos Uma sequência de dígitos de 0 a 9.
, Um separador de milhares específico da cultura. O separador de milhares da cultura especificada por provider pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowThousands.
. Um símbolo de vírgula decimal específico de cultura. O símbolo da vírgula decimal da cultura especificada por provider pode ser exibido em s caso style inclua o sinalizador NumberStyles.AllowDecimalPoint.
Fractional_digits Uma ou mais ocorrências de dígito 0. Os dígitos fracionários só podem ser exibidos em s caso style inclua o sinalizador NumberStyles.AllowDecimalPoint.
e O caractere 'e' ou 'E', que indica se o valor é representado na notação exponencial. O parâmetro s pode representar um número em notação exponencial caso style inclua o sinalizador NumberStyles.AllowExponent.
hexdigits Uma sequência de dígitos hexadecimais de 0 a f ou de 0 a F.

Observação

Todos os caracteres NUL de terminação (U+0000) no s são ignorados pela operação de análise, independentemente do valor do style argumento.

Uma cadeia de caracteres apenas com dígitos decimais (que corresponde ao sinalizador NumberStyles.None ) sempre é analisada com êxito. A maioria dos elementos de controle dos membros NumberStyles restantes que podem estar, mas que não precisam estar presentes nessa cadeia de caracteres de entrada. A tabela a seguir indica como os membros NumberStyles individuais afetam os elementos que podem estar presentes em s.

Valores NumberStyles não compostos Elementos permitidos em s além de dígitos
NumberStyles.None Somente dígitos decimais.
NumberStyles.AllowDecimalPoint O ponto decimal (.) e fractional_digits elementos. No entanto, fractional_digits deve consistir em apenas um ou mais 0 dígitos ou o método retorna false.
NumberStyles.AllowExponent O parâmetro s também pode usar notação exponencial. Se s representar um número na notação exponencial, ele deverá representar um inteiro dentro do intervalo do tipo de Int32 dados sem um componente fracionário diferente de zero.
NumberStyles.AllowLeadingWhite O elemento ws no início de s.
NumberStyles.AllowTrailingWhite O elemento ws no final de s.
NumberStyles.AllowLeadingSign Um sinal pode aparecer antes dos dígitos.
NumberStyles.AllowTrailingSign Um sinal pode aparecer após dígitos.
NumberStyles.AllowParentheses O elemento sinal na forma de parênteses que incluem o valor numérico.
NumberStyles.AllowThousands O elemento separador de milhares (,).
NumberStyles.AllowCurrencySymbol O $ elemento .
NumberStyles.Currency Todos os elementos. O parâmetro s não pode representar um número hexadecimal ou um número em notação exponencial.
NumberStyles.Float O elemento ws no início ou no final de s, assina no início de se o símbolo de ponto decimal (.). O parâmetro s também pode usar notação exponencial.
NumberStyles.Number Os elementos ws, sign, separador de milhares (,) e ponto decimal (.).
NumberStyles.Any Todos os estilos, exceto caso s não possa representar um número hexadecimal.

Se o NumberStyles.AllowHexSpecifier sinalizador for usado, s deverá ser um valor hexadecimal sem um prefixo. Por exemplo, "C9AF3" analisa com êxito, mas "0xC9AF3" não. Os únicos outros sinalizadores que podem estar presentes em style são NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. (A NumberStyles enumeração tem um estilo composto, NumberStyles.HexNumber, que inclui os dois sinalizadores de espaço em branco.)

O parâmetro provider é uma implementação de IFormatProvider, como um objeto CultureInfo ou um objeto NumberFormatInfo, cujo método GetFormat retorna um objeto NumberFormatInfo. O objeto NumberFormatInfo fornece informações específicas da cultura sobre o formato de s. Caso provider seja null, o objeto NumberFormatInfo da cultura atual é usado.

Confira também

Aplica-se a