BigInteger.TryParse Método

Definição

Tenta converter a representação da cadeia de um número para o seu BigInteger equivalente e devolve um valor que indica se a conversão foi bem-sucedida.

Sobrecargas

Name Description
TryParse(ReadOnlySpan<Char>, BigInteger)

Tenta converter a representação de um número contido no intervalo de caracteres só de leitura especificado para o seu BigInteger equivalente, e retorna um valor que indica se a conversão foi bem-sucedida.

TryParse(String, BigInteger)

Tenta converter a representação da cadeia de um número para o seu BigInteger equivalente e devolve um valor que indica se a conversão foi bem-sucedida.

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

Tenta converter a representação da cadeia de um número para o seu BigInteger equivalente e devolve um valor que indica se a conversão foi bem-sucedida.

TryParse(String, NumberStyles, IFormatProvider, BigInteger)

Tenta converter a representação em cadeia de um número num estilo especificado e formato específico de cultura para o seu BigInteger equivalente, e retorna um valor que indica se a conversão teve sucesso.

TryParse(ReadOnlySpan<Char>, BigInteger)

Tenta converter a representação de um número contido no intervalo de caracteres só de leitura especificado para o seu BigInteger equivalente, e retorna um valor que indica se a conversão foi bem-sucedida.

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

Parâmetros

value
ReadOnlySpan<Char>

A representação de um número como um intervalo de caracteres apenas de leitura.

result
BigInteger

Quando este método retorna, contém o BigInteger equivalente ao número contido em value, ou zero (0) se a conversão falhar. A conversão falha se o value parâmetro for um intervalo de caracteres vazio ou não for do formato correto. Este parâmetro é passado sem inicializar.

Devoluções

true se value foi convertido com sucesso; caso contrário, false.

Ver também

Aplica-se a

TryParse(String, BigInteger)

Tenta converter a representação da cadeia de um número para o seu BigInteger equivalente e devolve um valor que indica se a conversão foi bem-sucedida.

public:
 static bool TryParse(System::String ^ value, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result);
public static bool TryParse(string value, out System.Numerics.BigInteger result);
static member TryParse : string * BigInteger -> bool
Public Shared Function TryParse (value As String, ByRef result As BigInteger) As Boolean

Parâmetros

value
String

A representação em cadeia de um número.

result
BigInteger

Quando este método retorna, contém o BigInteger equivalente ao número contido em value, ou zero (0) se a conversão falhar. A conversão falha se o value parâmetro for null ou não do formato correto. Este parâmetro é passado sem inicializar.

Devoluções

true se value foi convertido com sucesso; caso contrário, false.

Exceções

value é null.

Exemplos

O exemplo seguinte utiliza o TryParse(String, BigInteger) método para instanciar dois BigInteger objetos. Se as conversões forem bem-sucedidas, multiplica cada objeto por outro número e depois chama o Compare método para determinar a relação entre os dois objetos.

BigInteger number1, number2;
bool succeeded1 = BigInteger.TryParse("-12347534159895123", out number1);
bool succeeded2 = BigInteger.TryParse("987654321357159852", out number2);
if (succeeded1 && succeeded2)
{
   number1 *= 3;
   number2 *= 2;
   switch (BigInteger.Compare(number1, number2))
   {
      case -1:
         Console.WriteLine("{0} is greater than {1}.", number2, number1);
         break;
      case 0:
         Console.WriteLine("{0} is equal to {1}.", number1, number2);
         break;
      case 1:
         Console.WriteLine("{0} is greater than {1}.", number1, number2);
         break;
   }
}
else
{
   if (!succeeded1)
      Console.WriteLine("Unable to initialize the first BigInteger value.");

   if (!succeeded2)
      Console.WriteLine("Unable to initialize the second BigInteger value.");
}
// The example displays the following output:
//      1975308642714319704 is greater than -37042602479685369.
    let mutable number1 = BigInteger.Zero
    let mutable number2 = BigInteger.Zero

    let succeeded1 = BigInteger.TryParse("-12347534159895123", &number1)
    let succeeded2 = BigInteger.TryParse("987654321357159852", &number2)

    if succeeded1 && succeeded2 then
        number1 <- number1 * 3I
        number2 <- number2 * 2I

        match BigInteger.Compare(number1, number2) with
        | -1 -> printfn $"{number2} is greater than {number2}."
        | 0 -> printfn $"{number1} is equal to {number2}."
        | 1
        | _ -> printfn $"{number1} is greater than {number2}."
    else
        if not succeeded1 then
            printfn "Unable to initialize the first BigInteger value."

        if not succeeded2 then
            printfn "Unable to initialize the second BigInteger value."

// The example displays the following output:
//      1975308642714319704 is greater than -37042602479685369.
Dim number1 As BigInteger = BigInteger.Zero
Dim number2 As BigInteger = BigInteger.Zero
Dim succeeded1 As Boolean = BigInteger.TryParse("-12347534159895123", number1)
Dim succeeded2 As Boolean = BigInteger.TryParse("987654321357159852", number2)
If succeeded1 AndAlso succeeded2
   number1 *= 3
   number2 *= 2
   Select Case BigInteger.Compare(number1, number2)
      Case -1
         Console.WriteLine("{0} is greater than {1}.", number2, number1)
      Case 0
         Console.WriteLine("{0} is equal to {1}.", number1, number2)
      Case 1
         Console.WriteLine("{0} is greater than {1}.", number1, number2)
   End Select      
Else
   If Not succeeded1 Then 
      Console.WriteLine("Unable to initialize the first BigInteger value.")
   End If
   If Not succeeded2 Then
      Console.WriteLine("Unable to initialize the second BigInteger value.")
   
   End If
End If
' The example displays the following output:
'      1975308642714319704 is greater than -37042602479685369.

Observações

O TryParse(String, BigInteger) método é como o Parse(String) método, exceto que ele não lança uma exceção se a conversão falhar. Este método elimina a necessidade de usar o tratamento de exceções para testar se um FormatException se value é inválido e não pode ser analisado com sucesso.

O value parâmetro deve ser a representação da cadeia de um número decimal na seguinte forma:

[ws][sinal]dígitos[ws]

Os elementos entre parênteses retos ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.

Elemento Description
ws Espaço em branco opcional.
assinar Um sinal opcional. Caracteres de signo válidos são determinados pelas NumberFormatInfo.NegativeSign propriedades e NumberFormatInfo.PositiveSign da cultura atual.
dígitos Uma sequência de dígitos decimais entre 0 e 9.

Note

A cadeia especificada pelo value parâmetro não pode conter separadores de grupo ou separadores decimais, nem pode ter uma parte decimal.

O value parâmetro é interpretado usando o NumberStyles.Integer estilo. Para além dos dígitos decimais, apenas espaços à frente e à frente com sinal à frente são permitidos. Para definir explicitamente os elementos de estilo com a informação de formatação específica da cultura que pode estar presente em value, chame o TryParse(String, NumberStyles, IFormatProvider, BigInteger) método.

O value parâmetro é analisado usando a informação de formatação num NumberFormatInfo objeto para a cultura atual. Para obter mais informações, veja NumberFormatInfo.CurrentInfo.

Esta sobrecarga interpreta todos os dígitos do value parâmetro como dígitos decimais. Para analisar a representação da cadeia de um número hexadecimal, chame-se a TryParse(String, NumberStyles, IFormatProvider, BigInteger) sobrecarga em vez disso.

Ver também

Aplica-se a

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

Tenta converter a representação da cadeia de um número para o seu BigInteger equivalente e devolve um valor que indica se a conversão foi bem-sucedida.

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

Parâmetros

value
ReadOnlySpan<Char>

A representação de um número como um intervalo de caracteres apenas de leitura.

style
NumberStyles

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

provider
IFormatProvider

Um objeto que fornece informação de formatação específica de cultura sobre value.

result
BigInteger

Quando este método retorna, contém o equivalente BigInteger ao número contido em value, ou Zero se a conversão falhou. A conversão falha se o value parâmetro for um espaço de caracteres vazio ou não estiver num formato compatível com style. Este parâmetro é passado sem inicializar.

Devoluções

true se value foi convertido com sucesso; caso contrário, false.

Exceções

style não é um NumberStyles valor.

-ou-

style inclui a AllowHexSpecifier bandeira de ou HexNumber juntamente com outro valor.

Observações

Esta sobrecarga é semelhante ao Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) método, exceto que não lança exceção se a conversão falhar. Este método elimina a necessidade de usar o tratamento de exceções para testar se um FormatException se value é inválido e não pode ser analisado com sucesso.

O style parâmetro define os elementos de estilo (como espaços em branco ou um sinal positivo ou negativo) que são permitidos no value parâmetro para que a operação de análise sintática tenha sucesso. Deve ser uma combinação de indicadores de bits da NumberStyles enumeração. Dependendo do valor de style, o value parâmetro pode incluir os seguintes elementos:

[ws][$][signo][dígitos,]dígitos[.fractional_digits][E[sign]exponential_digits][ws]

Se o style parâmetro incluir AllowHexSpecifier, o value parâmetro pode incluir os seguintes elementos:

[ws]hexdigits[ws]

Os elementos entre parênteses retos ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.

Elemento Description
ws Espaço em branco opcional. O espaço em branco pode aparecer no início de value if style inclui a NumberStyles.AllowLeadingWhite bandeira, ou no final de value if style inclui a NumberStyles.AllowTrailingWhite bandeira.
$ Um símbolo monetário específico de cada cultura. A sua posição em value é definida pela CurrencyPositivePattern propriedade do NumberFormatInfo objeto devolvida pelo GetFormat método do provider parâmetro. O símbolo da moeda pode aparecer se valuestyle incluir a NumberStyles.AllowCurrencySymbol bandeira.
assinar Um sinal opcional. O sinal pode aparecer no início de value se incluir a NumberStyles.AllowLeadingSign bandeira, e pode aparecer no final de value se style incluir a NumberStyles.AllowTrailingSignstyle bandeira. Parênteses podem ser usados value para indicar um valor negativo se style incluir a NumberStyles.AllowParentheses bandeira.
dígitos Uma sequência de dígitos de 0 a 9.
, Um separador de grupo específico de cultura. O separador de grupo da cultura especificado por provider pode aparecer em value se style incluir a NumberStyles.AllowThousands bandeira.
. Um símbolo de ponto decimal específico para cada cultura. O símbolo da vírgula decimal da cultura especificado por provider pode aparecer em value se style incluir a NumberStyles.AllowDecimalPoint bandeira.
fractional_digits Uma ou mais ocorrências do dígito 0. Os dígitos fracionários só podem aparecer se valuestyle incluir a NumberStyles.AllowDecimalPoint bandeira.
E O carácter "e" ou "E", que indica que o valor é representado em notação exponencial (científica). O value parâmetro pode representar um número em notação exponencial se style incluir a NumberStyles.AllowExponent bandeira.
exponential_digits Uma sequência de dígitos de 0 a 9. O value parâmetro pode representar um número em notação exponencial se style incluir a NumberStyles.AllowExponent bandeira.
Hexdigits Uma sequência de dígitos hexadecimais de 0 a f, ou de 0 a F.

Note

Quaisquer caracteres NUL terminantes (U+0000) em s são ignorados pela operação de análise, independentemente do valor do style argumento.

Valores não compostos NumberStyles Elementos permitidos em valor além dos dígitos
None Apenas dígitos decimais.
AllowDecimalPoint A vírgula decimal (.) e fractional_digits elementos. No entanto, fractional_digits deve consistir apenas em um ou mais dígitos 0, ou o método devolve false.
AllowExponent O carácter "e" ou "E", que indica notação exponencial, juntamente com exponential_digits. Se value representa um número em notação exponencial, não pode ter um componente fracionário não nulo.
AllowLeadingWhite O elemento ws no início de value.
AllowTrailingWhite O elemento ws no final de value.
AllowLeadingSign O elemento de sinal antes dos dígitos.
AllowTrailingSign O elemento de sinal após os dígitos.
AllowParentheses O elemento do signo na forma de parênteses que envolvem o valor numérico.
AllowThousands O elemento separador de grupo (,).
AllowCurrencySymbol O elemento da moeda ($).
Currency Todos os elementos. No entanto, value não pode representar um número hexadecimal ou um número em notação exponencial.
Float O elemento ws no início ou fim de value, sinal no início de value, e o símbolo da vírgula decimal (.). O value parâmetro também pode usar notação exponencial.
Number Os elementos ws, signo, separador de grupo (,) e ponto decimal (.).
Any Todos os elementos. No entanto, value não pode representar um número hexadecimal.

Se a NumberStyles.AllowHexSpecifier bandeira for usada, value deve ser um valor hexadecimal. As únicas outras bandeiras que podem estar presentes em style e NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhite. (A NumberStyles enumeração tem um estilo composto, HexNumber, que inclui ambas as bandeiras de espaço em branco.)

O provider parâmetro é uma IFormatProvider implementação. O seu GetFormat método devolve um NumberFormatInfo objeto que fornece informação específica da cultura sobre o formato de value. O provider parâmetro pode ser qualquer um dos seguintes:

  • Um CultureInfo objeto que representa a cultura que fornece informação de formatação. O seu GetFormat método devolve o NumberFormatInfo objeto que fornece informação numérica de formatação para essa cultura.

  • Um NumberFormatInfo objeto que fornece informação numérica de formatação. (A sua implementação de GetFormat simplesmente devolve-se a si própria.)

  • Um objeto personalizado que implementa IFormatProvider. O seu GetFormat método instancia e devolve o NumberFormatInfo objeto que fornece a informação de formatação.

Se provider for null, o NumberFormatInfo objeto para a cultura atual é usado.

Ver também

Aplica-se a

TryParse(String, NumberStyles, IFormatProvider, BigInteger)

Tenta converter a representação em cadeia de um número num estilo especificado e formato específico de cultura para o seu BigInteger equivalente, e retorna um valor que indica se a conversão teve sucesso.

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

Parâmetros

value
String

A representação em cadeia de um número. A cadeia é interpretada usando o estilo especificado por style.

style
NumberStyles

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

provider
IFormatProvider

Um objeto que fornece informação de formatação específica de cultura sobre value.

result
BigInteger

Quando este método retorna, contém o equivalente BigInteger ao número contido em value, ou Zero se a conversão falhou. A conversão falha se o value parâmetro estiver null ou não num formato compatível com style. Este parâmetro é passado sem inicializar.

Devoluções

true se o value parâmetro foi convertido com sucesso; caso contrário, false.

Exceções

style não é um NumberStyles valor.

-ou-

style inclui a AllowHexSpecifier bandeira de ou HexNumber juntamente com outro valor.

Exemplos

O exemplo seguinte faz algumas chamadas ao TryParse(String, NumberStyles, IFormatProvider, BigInteger) método usando várias combinações de valores para os style parâmetros e.provider

string numericString;
BigInteger number = BigInteger.Zero;

// Call TryParse with default values of style and provider.
numericString = "  -300   ";
if (BigInteger.TryParse(numericString, NumberStyles.Integer,
                       null, out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with the default value of style and
// a provider supporting the tilde as negative sign.
numericString = "  -300   ";
if (BigInteger.TryParse(numericString, NumberStyles.Integer,
                       new BigIntegerFormatProvider(), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with only AllowLeadingWhite and AllowTrailingWhite.
// Method returns false because of presence of negative sign.
numericString = "  -500   ";
if (BigInteger.TryParse(numericString,
                        NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite,
                        new BigIntegerFormatProvider(), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with AllowHexSpecifier and a hex value.
numericString = "F14237FFAAC086455192";
if (BigInteger.TryParse(numericString,
                        NumberStyles.AllowHexSpecifier,
                        null, out number))
   Console.WriteLine("'{0}' was converted to {1} (0x{1:x}).",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with AllowHexSpecifier and a negative hex value.
// Conversion fails because of presence of negative sign.
numericString = "-3af";
if (BigInteger.TryParse(numericString, NumberStyles.AllowHexSpecifier,
                       new BigIntegerFormatProvider(), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with only NumberStyles.None.
// Conversion fails because of presence of white space and sign.
numericString = " -300 ";
if (BigInteger.TryParse(numericString, NumberStyles.None,
                       new BigIntegerFormatProvider(), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
// Conversion fails because the string is formatted for the en-US culture.
numericString = "9,031,425,666,123,546.00";
if (BigInteger.TryParse(numericString, NumberStyles.Any,
                       new CultureInfo("fr-FR"), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
// Conversion succeeds because the string is properly formatted
// For the fr-FR culture.
numericString = "9 031 425 666 123 546,00";
if (BigInteger.TryParse(numericString, NumberStyles.Any,
                       new CultureInfo("fr-FR"), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);
// The example displays the following output:
//    '  -300   ' was converted to -300.
//    Conversion of '  -300   ' to a BigInteger failed.
//    Conversion of '  -500   ' to a BigInteger failed.
//    'F14237FFAAC086455192' was converted to -69613977002644837412462 (0xf14237ffaac086455192).
//    Conversion of '-3af' to a BigInteger failed.
//    Conversion of ' -300 ' to a BigInteger failed.
//    Conversion of '9,031,425,666,123,546.00' to a BigInteger failed.
//    '9 031 425 666 123 546,00' was converted to 9031425666123546.
    // Call TryParse with default values of style and provider.
    let numericString = "  -300   "

    match BigInteger.TryParse(numericString, NumberStyles.Integer, null) with
    | true, number -> printfn $"The string '{numericString}' parses to {number}"
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

    // Call TryParse with the default value of style and
    // a provider supporting the tilde as negative sign.
    let numericString = "  -300   "

    match BigInteger.TryParse(numericString, NumberStyles.Integer, new BigIntegerFormatProvider()) with
    | true, number -> printfn $"The string '{numericString}' parses to {number}"
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

    // Call TryParse with only AllowLeadingWhite and AllowTrailingWhite.
    // Method returns false because of presence of negative sign.
    let numericString = "  -500   "

    match
        BigInteger.TryParse(
            numericString,
            NumberStyles.AllowLeadingWhite ||| NumberStyles.AllowTrailingWhite,
            new BigIntegerFormatProvider()
        )
    with
    | true, number -> printfn $"The string '{numericString}' parses to {number}"
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

    // Call TryParse with AllowHexSpecifier and a hex value.
    let numericString = "F14237FFAAC086455192"

    match BigInteger.TryParse(numericString, NumberStyles.AllowHexSpecifier, null) with
    | true, number -> printfn $"The string '{numericString}' parses to {number}, or 0x{number:x}."
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

    // Call TryParse with AllowHexSpecifier and a negative hex value.
    // Conversion fails because of presence of negative sign.
    let numericString = "-3af"

    match BigInteger.TryParse(numericString, NumberStyles.AllowHexSpecifier, null) with
    | true, number -> printfn $"The string '{numericString}' parses to {number}, or 0x{number:x}."
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

    // Call TryParse with only NumberStyles.None.
    // Conversion fails because of presence of white space and sign.
    let numericString = " -300 "

    match BigInteger.TryParse(numericString, NumberStyles.None, new BigIntegerFormatProvider()) with
    | true, number -> printfn $"The string '{numericString}' parses to {number}"
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

    // Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
    // Conversion fails because the string is formatted for the en-US culture.
    let numericString = "9,031,425,666,123,546.00"

    match BigInteger.TryParse(numericString, NumberStyles.Any, new CultureInfo("fr-FR")) with
    | true, number -> printfn $"The string '{numericString}' parses to {number}"
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

    // Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
    // Conversion succeeds because the string is properly formatted
    // For the fr-FR culture.
    let numericString = "9 031 425 666 123 546,00"

    match BigInteger.TryParse(numericString, NumberStyles.Any, new CultureInfo("fr-FR")) with
    | true, number -> printfn $"The string '{numericString}' parses to {number}"
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

// The example displays the following output:
//    '  -300   ' was converted to -300.
//    Conversion of '  -300   ' to a BigInteger failed.
//    Conversion of '  -500   ' to a BigInteger failed.
//    'F14237FFAAC086455192' was converted to -69613977002644837412462 (0xf14237ffaac086455192).
//    Conversion of '-3af' to a BigInteger failed.
//    Conversion of ' -300 ' to a BigInteger failed.
//    Conversion of '9,031,425,666,123,546.00' to a BigInteger failed.
//    '9 031 425 666 123 546,00' was converted to 9031425666123546.
Dim numericString As String
Dim number As BigInteger = BigInteger.Zero

' Call TryParse with default values of style and provider.
numericString = "  -300   "
If BigInteger.TryParse(numericString, NumberStyles.Integer,
                       Nothing, number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If                                             

' Call TryParse with the default value of style and 
' a provider supporting the tilde as negative sign.
numericString = "  -300   "
If BigInteger.TryParse(numericString, NumberStyles.Integer,
                       New BigIntegerFormatProvider(), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If                                             

' Call TryParse with only AllowLeadingWhite and AllowTrailingWhite.
' Method returns false because of presence of negative sign.
numericString = "  -500   "
If BigInteger.TryParse(numericString,
                    NumberStyles.AllowLeadingWhite Or NumberStyles.AllowTrailingWhite,
                    New BigIntegerFormatProvider(), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If                                             

' Call TryParse with AllowHexSpecifier and a hex value.
numericString = "F14237FFAAC086455192"
If BigInteger.TryParse(numericString,
                    NumberStyles.AllowHexSpecifier,
                    Nothing, number) Then
   Console.WriteLine("'{0}' was converted to {1} (0x{1:x}).",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If                                             

' Call TryParse with AllowHexSpecifier and a negative hex value.
' Conversion fails because of presence of negative sign.
numericString = "-3af"
If BigInteger.TryParse(numericString, NumberStyles.AllowHexSpecifier,
                       New BigIntegerFormatProvider(), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If                                             

' Call TryParse with only NumberStyles.None.
' Conversion fails because of presence of white space and sign.
numericString = " -300 "
If BigInteger.TryParse(numericString, NumberStyles.None,
                       New BigIntegerFormatProvider(), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If 
                                            
' Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
' Conversion fails because the string is formatted for the en-US culture.
numericString = "9,031,425,666,123,546.00"
If BigInteger.TryParse(numericString, NumberStyles.Any,
                       New CultureInfo("fr-FR"), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If

' Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
' Conversion succeeds because the string is properly formatted 
' For the fr-FR culture.
numericString = "9 031 425 666 123 546,00"
If BigInteger.TryParse(numericString, NumberStyles.Any,
                       New CultureInfo("fr-FR"), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If
' The example displays the following output:
'    '  -300   ' was converted to -300.
'    Conversion of '  -300   ' to a BigInteger failed.
'    Conversion of '  -500   ' to a BigInteger failed.
'    'F14237FFAAC086455192' was converted to -69613977002644837412462 (0xf14237ffaac086455192).
'    Conversion of '-3af' to a BigInteger failed.
'    Conversion of ' -300 ' to a BigInteger failed.
'    Conversion of '9,031,425,666,123,546.00' to a BigInteger failed.
'    '9 031 425 666 123 546,00' was converted to 9031425666123546.

Várias das chamadas individuais ao TryParse(String, NumberStyles, IFormatProvider, BigInteger) método passam por uma instância da classe seguinte BigIntegerFormatProvider , que define um tilde (~) como sinal negativo.

public class BigIntegerFormatProvider : IFormatProvider
{
   public object GetFormat(Type formatType)
   {
      if (formatType == typeof(NumberFormatInfo))
      {
         NumberFormatInfo numberFormat = new NumberFormatInfo();
         numberFormat.NegativeSign = "~";
         return numberFormat;
      }
      else
      {
         return null;
      }
   }
}
type BigIntegerFormatProvider() =
    interface IFormatProvider with
        member _.GetFormat(formatType: Type) =
            if formatType = typeof<NumberFormatInfo> then
                let numberFormat = new NumberFormatInfo()
                numberFormat.NegativeSign <- "~"
                numberFormat
            else
                null
Public Class BigIntegerFormatProvider : Implements IFormatProvider
   Public Function GetFormat(formatType As Type) As Object _
                            Implements IFormatProvider.GetFormat
      If formatType Is GetType(NumberFormatInfo) Then
         Dim numberFormat As New NumberFormatInfo
         numberFormat.NegativeSign = "~"
         Return numberFormat
      Else
         Return Nothing
      End If      
   End Function
End Class

Observações

O TryParse(String, NumberStyles, IFormatProvider, BigInteger) método é como o Parse(String, NumberStyles, IFormatProvider) método, exceto que ele não lança uma exceção se a conversão falhar. Este método elimina a necessidade de usar o tratamento de exceções para testar se um FormatException se value é inválido e não pode ser analisado com sucesso.

O style parâmetro define os elementos de estilo (como espaços em branco ou um sinal positivo ou negativo) que são permitidos no value parâmetro para que a operação de análise sintática tenha sucesso. Deve ser uma combinação de indicadores de bits da NumberStyles enumeração. Dependendo do valor de style, o value parâmetro pode incluir os seguintes elementos:

[ws][$][signo][dígitos,]dígitos[.fractional_digits][E[sign]exponential_digits][ws]

Se o style parâmetro incluir AllowHexSpecifier, o value parâmetro pode incluir os seguintes elementos:

[ws]hexdigits[ws]

Os elementos entre parênteses retos ([ e ]) são opcionais. A tabela a seguir descreve cada elemento.

Elemento Description
ws Espaço em branco opcional. O espaço em branco pode aparecer no início de value if style inclui a NumberStyles.AllowLeadingWhite bandeira, ou no final de value if style inclui a NumberStyles.AllowTrailingWhite bandeira.
$ Um símbolo monetário específico de cada cultura. A sua posição na cadeia é definida pela CurrencyPositivePattern propriedade do NumberFormatInfo objeto devolvida pelo GetFormat método do provider parâmetro. O símbolo da moeda pode aparecer se valuestyle incluir a NumberStyles.AllowCurrencySymbol bandeira.
assinar Um sinal opcional. O sinal pode aparecer no início de value se incluir a NumberStyles.AllowLeadingSign bandeira, e pode aparecer no final de value se style incluir a NumberStyles.AllowTrailingSignstyle bandeira. Parênteses podem ser usados value para indicar um valor negativo se style incluir a NumberStyles.AllowParentheses bandeira.
dígitos Uma sequência de dígitos de 0 a 9.
, Um separador de grupo específico de cultura. O separador de grupo da cultura especificado por provider pode aparecer em value se style incluir a NumberStyles.AllowThousands bandeira.
. Um símbolo de ponto decimal específico para cada cultura. O símbolo da vírgula decimal da cultura especificado por provider pode aparecer em value se style incluir a NumberStyles.AllowDecimalPoint bandeira.
fractional_digits Uma ou mais ocorrências do dígito 0. Os dígitos fracionários só podem aparecer se valuestyle incluir a NumberStyles.AllowDecimalPoint bandeira.
E O carácter "e" ou "E", que indica que o valor é representado em notação exponencial (científica). O value parâmetro pode representar um número em notação exponencial se style incluir a NumberStyles.AllowExponent bandeira.
exponential_digits Uma sequência de dígitos de 0 a 9. O value parâmetro pode representar um número em notação exponencial se style incluir a NumberStyles.AllowExponent bandeira.
Hexdigits Uma sequência de dígitos hexadecimais de 0 a f, ou de 0 a F.

Note

Quaisquer caracteres NUL terminantes (U+0000) em s são ignorados pela operação de análise, independentemente do valor do style argumento.

Uma cadeia apenas com dígitos decimais (que corresponde à NumberStyles.None bandeira) faz sempre análise com sucesso. A maioria dos membros restantes NumberStyles controla elementos que podem estar presentes, mas que não são obrigados a estar presentes, nesta cadeia de entrada. A tabela seguinte indica como os membros individuais NumberStyles afetam os elementos que podem estar presentes em value.

Valores não compostos NumberStyles Elementos permitidos em valor além dos dígitos
None Apenas dígitos decimais.
AllowDecimalPoint A vírgula decimal (.) e fractional_digits elementos. No entanto, fractional_digits deve consistir apenas em um ou mais dígitos 0, ou o método devolve false.
AllowExponent O carácter "e" ou "E", que indica notação exponencial, juntamente com exponential_digits. Se value representa um número em notação exponencial, não pode ter um componente fracionário não nulo.
AllowLeadingWhite O elemento ws no início de value.
AllowTrailingWhite O elemento ws no final de value.
AllowLeadingSign O elemento de sinal antes dos dígitos.
AllowTrailingSign O elemento de sinal após os dígitos.
AllowParentheses O elemento do signo na forma de parênteses que envolvem o valor numérico.
AllowThousands O elemento separador de grupo (,).
AllowCurrencySymbol O elemento da moeda ($).
Currency Todos os elementos. No entanto, value não pode representar um número hexadecimal ou um número em notação exponencial.
Float O elemento ws no início ou fim de value, sinal no início de value, e o símbolo da vírgula decimal (.). O value parâmetro também pode usar notação exponencial.
Number Os elementos ws, signo, separador de grupo (,) e ponto decimal (.).
Any Todos os elementos. No entanto, value não pode representar um número hexadecimal.

Importante

Se usar o TryParse método para fazer round-trip da representação de string de um BigInteger valor que foi gerado pelo ToString método, deve usar o BigInteger.ToString(String) método com o especificador do formato "R" para gerar a representação string do BigInteger valor. Caso contrário, a representação em cadeia do BigInteger preserva apenas os 50 dígitos mais significativos do valor original, e os dados podem perder-se quando se utiliza o TryParse método para restaurar o BigInteger valor.

Se a NumberStyles.AllowHexSpecifier bandeira for usada, value deve ser um valor hexadecimal. As únicas outras bandeiras que podem estar presentes em style e NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhite. (A NumberStyles enumeração tem um estilo composto, HexNumber, que inclui ambas as bandeiras de espaço em branco.)

Note

Se value for a representação em cadeia de um número hexadecimal, não pode ser precedida por qualquer decoração (como 0x ou &h) que a diferencie como número hexadecimal. Isto faz com que a conversão falhe.

Se value for uma cadeia hexadecimal, o TryParse(String, NumberStyles, IFormatProvider, BigInteger) método interpreta value como um número negativo armazenado usando a representação do complemento de dois se os seus dois primeiros dígitos hexadecimais forem maiores ou iguais a 0x80. Por outras palavras, o método interpreta o bit de ordem mais alta do primeiro byte em value como o bit de sinal. Para garantir que uma cadeia hexadecimal é corretamente interpretada como um número positivo, o primeiro dígito em value deve ter um valor zero. Por exemplo, o método interpreta 0x80 como um valor negativo, mas interpreta como ou 0x0800x0080 como um valor positivo. O exemplo seguinte ilustra a diferença entre cadeias hexadecimais que representam valores negativos e positivos.

using System;
using System.Globalization;
using System.Numerics;

public class Example
{
   public static void Main()
   {
      string[] hexStrings = { "80", "E293", "F9A2FF", "FFFFFFFF",
                              "080", "0E293", "0F9A2FF", "0FFFFFFFF",
                              "0080", "00E293", "00F9A2FF", "00FFFFFFFF" };
      BigInteger number = BigInteger.Zero;

      foreach (string hexString in hexStrings)
      {
         if (BigInteger.TryParse(hexString, NumberStyles.AllowHexSpecifier,
                                 null, out number))
            Console.WriteLine("Converted 0x{0} to {1}.", hexString, number);
         else
            Console.WriteLine("Cannot convert '{0}' to a BigInteger.", hexString);
      }
   }
}
// The example displays the following output:
//       Converted 0x80 to -128.
//       Converted 0xE293 to -7533.
//       Converted 0xF9A2FF to -417025.
//       Converted 0xFFFFFFFF to -1.
//       Converted 0x080 to 128.
//       Converted 0x0E293 to 58003.
//       Converted 0x0F9A2FF to 16360191.
//       Converted 0x0FFFFFFFF to 4294967295.
//       Converted 0x0080 to 128.
//       Converted 0x00E293 to 58003.
//       Converted 0x00F9A2FF to 16360191.
//       Converted 0x00FFFFFFFF to 4294967295.
open System.Globalization
open System.Numerics

let hexStrings =
    [| "80"
       "E293"
       "F9A2FF"
       "FFFFFFFF"
       "080"
       "0E293"
       "0F9A2FF"
       "0FFFFFFFF"
       "0080"
       "00E293"
       "00F9A2FF"
       "00FFFFFFFF" |]

for hexString in hexStrings do
    match BigInteger.TryParse(hexString, NumberStyles.AllowHexSpecifier, null) with
    | true, number -> printfn $"Converted 0x{hexString} to {number}."
    | _ -> printfn $"Cannot convert '{hexString}' to a BigInteger."

// The example displays the following output:
//       Converted 0x80 to -128.
//       Converted 0xE293 to -7533.
//       Converted 0xF9A2FF to -417025.
//       Converted 0xFFFFFFFF to -1.
//       Converted 0x080 to 128.
//       Converted 0x0E293 to 58003.
//       Converted 0x0F9A2FF to 16360191.
//       Converted 0x0FFFFFFFF to 4294967295.
//       Converted 0x0080 to 128.
//       Converted 0x00E293 to 58003.
//       Converted 0x00F9A2FF to 16360191.
//       Converted 0x00FFFFFFFF to 4294967295.
Imports System.Globalization
Imports System.Numerics

Module Example
   Public Sub Main()
      Dim hexStrings() As String = { "80", "E293", "F9A2FF", "FFFFFFFF", 
                                     "080", "0E293", "0F9A2FF", "0FFFFFFFF",  
                                     "0080", "00E293", "00F9A2FF", "00FFFFFFFF" }
      Dim number As BigInteger = BigInteger.Zero
      
      For Each hexString As String In hexStrings
         If BigInteger.TryParse(hexString, NumberStyles.AllowHexSpecifier, 
                                Nothing, number) Then
            Console.WriteLine("Converted 0x{0} to {1}.", hexString, number)
         Else
            Console.WriteLine("Cannot convert '{0}' to a BigInteger.", hexString)
         End If
      Next         
   End Sub
End Module
' The example displays the following output:
'       Converted 0x80 to -128.
'       Converted 0xE293 to -7533.
'       Converted 0xF9A2FF to -417025.
'       Converted 0xFFFFFFFF to -1.
'       Converted 0x080 to 128.
'       Converted 0x0E293 to 58003.
'       Converted 0x0F9A2FF to 16360191.
'       Converted 0x0FFFFFFFF to 4294967295.
'       Converted 0x0080 to 128.
'       Converted 0x00E293 to 58003.
'       Converted 0x00F9A2FF to 16360191.
'       Converted 0x00FFFFFFFF to 4294967295.

O provider parâmetro é uma IFormatProvider implementação. O seu GetFormat método devolve um NumberFormatInfo objeto que fornece informação específica da cultura sobre o formato de value. O provider parâmetro pode ser qualquer um dos seguintes:

  • Um CultureInfo objeto que representa a cultura que fornece informação de formatação. O seu GetFormat método devolve o NumberFormatInfo objeto que fornece informação numérica de formatação para essa cultura.

  • Um NumberFormatInfo objeto que fornece informação numérica de formatação. (A sua implementação de GetFormat simplesmente devolve-se a si própria.)

  • Um objeto personalizado que implementa IFormatProvider. O seu GetFormat método instancia e devolve o NumberFormatInfo objeto que fornece a informação de formatação.

Se provider for null, o NumberFormatInfo objeto para a cultura atual é usado.

Ver também

Aplica-se a