BigInteger.TryParse Método

Definición

Intenta convertir la representación en forma de cadena de un número en su equivalente BigInteger y devuelve un valor que indica si la conversión tuvo éxito.

Sobrecargas

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

Intenta convertir la representación en forma de cadena de un número en su equivalente BigInteger y devuelve un valor que indica si la conversión tuvo éxito.

TryParse(String, IFormatProvider, BigInteger)

Intenta analizar una cadena en un valor.

TryParse(ReadOnlySpan<Char>, IFormatProvider, BigInteger)

Intenta analizar un intervalo de caracteres en un valor.

TryParse(String, BigInteger)

Intenta convertir la representación en forma de cadena de un número en su equivalente BigInteger y devuelve un valor que indica si la conversión tuvo éxito.

TryParse(ReadOnlySpan<Char>, BigInteger)

Intenta convertir la representación de un número incluido en el intervalo de caracteres de solo lectura especificado en su equivalente BigInteger y devuelve un valor que indica si la conversión se ha realizado correctamente.

TryParse(String, NumberStyles, IFormatProvider, BigInteger)

Intenta convertir la representación de cadena de un número con un estilo específico y un formato específico de la referencia cultural en su equivalente de BigInteger y devuelve un valor que indica si la conversión fue correcta.

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

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Intenta convertir la representación en forma de cadena de un número en su equivalente BigInteger y devuelve un valor que indica si la conversión tuvo éxito.

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, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result) = System::Numerics::INumberBase<System::Numerics::BigInteger>::TryParse;
public static bool TryParse (ReadOnlySpan<char> value, System.Globalization.NumberStyles style, IFormatProvider? provider, 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>

Representación de un número como un intervalo de solo lectura de caracteres.

style
NumberStyles

Combinación bit a bit de los valores de enumeración que indica los elementos de estilo que pueden estar presentes en value. Un valor que se especifica de forma habitual es Integer.

provider
IFormatProvider

Objeto que proporciona información de formato específica de la referencia cultural acerca de value.

result
BigInteger

Cuando este método vuelve, contiene el equivalente BigInteger al número contenido en value, o Zero si se produjo un error en la conversión. Se produce un error de conversión si el parámetro value es un intervalo de caracteres vacío o no tiene un formato conforme con style. Este parámetro se pasa sin inicializar.

Devoluciones

true si value se convirtió correctamente; en caso contrario, false.

Excepciones

style no es un valor NumberStyles.

o bien

style incluye la marca AllowHexSpecifier o HexNumber junto con otro valor.

Comentarios

Esta sobrecarga es similar al Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) método , salvo que no produce una excepción si se produce un error en la conversión. Este método elimina la necesidad de usar el control de excepciones para probar si FormatExceptionvalue no es válido y no se puede analizar correctamente.

El style parámetro define los elementos de estilo (como espacios en blanco o un signo positivo o negativo) que se permiten en el value parámetro para que la operación de análisis se realice correctamente. Debe ser una combinación de marcas de bits de la NumberStyles enumeración . Según el valor de style, el value parámetro puede incluir los siguientes elementos:

[ws] [$][sign][digits,]digits[.fractional_digits][E[sign]exponential_digits][ws]

Si el style parámetro incluye AllowHexSpecifier, el value parámetro puede incluir los siguientes elementos:

[ws] hexdigits[ws]

Los elementos de los corchetes ([ y ]) son opcionales. En esta tabla se describe cada elemento.

Elemento Descripción
ws Espacio en blanco opcional. El espacio en blanco puede aparecer al principio de value si incluye la NumberStyles.AllowLeadingWhite marca o al final de value si style incluye la NumberStyles.AllowTrailingWhite marca .style
$ Símbolo de moneda específico de la referencia cultural. Su posición en value se define mediante la CurrencyPositivePattern propiedad del NumberFormatInfo objeto devuelto por el GetFormat método del provider parámetro . El símbolo de moneda puede aparecer en value si style incluye la NumberStyles.AllowCurrencySymbol marca .
sign Un signo opcional. El signo puede aparecer al principio de value si incluye la NumberStyles.AllowLeadingSign marca y puede aparecer al final de value si style incluye la NumberStyles.AllowTrailingSignstyle marca . Los paréntesis se pueden usar en value para indicar un valor negativo si style incluye la NumberStyles.AllowParentheses marca .
dígitos Secuencia de dígitos de 0 a 9.
, Separador de grupo específico de la referencia cultural. El separador de grupo de la referencia cultural especificada por provider puede aparecer en value si style incluye la NumberStyles.AllowThousands marca .
. Símbolo de separador decimal específico de la referencia cultural. El símbolo decimal de la referencia cultural especificada por provider puede aparecer en value si style incluye la NumberStyles.AllowDecimalPoint marca .
fractional_digits Una o varias apariciones del dígito 0. Los dígitos fraccionarios solo pueden aparecer en value si style incluye la NumberStyles.AllowDecimalPoint marca .
E Carácter "e" o "E", que indica que el valor se representa en notación exponencial (científica). El value parámetro puede representar un número en notación exponencial si style incluye la NumberStyles.AllowExponent marca .
exponential_digits Secuencia de dígitos de 0 a 9. El value parámetro puede representar un número en notación exponencial si style incluye la NumberStyles.AllowExponent marca .
hexdigits Secuencia de dígitos hexadecimales de 0 a f, o de 0 a F.

Nota

La operación de análisis omite los caracteres NUL (U+0000) terminados, s independientemente del valor del style argumento.

Valores no compuestos NumberStyles Elementos permitidos en el valor además de dígitos
None Solo dígitos decimales.
AllowDecimalPoint Los elementos decimales (.) y fractional_digits . Sin embargo, fractional_digits solo debe constar de uno o más dígitos, o el método devuelve false.
AllowExponent Carácter "e" o "E", que indica la notación exponencial, junto con exponential_digits. Si value representa un número en notación exponencial, no puede tener un componente fraccionaria distinto de cero.
AllowLeadingWhite Elemento ws al principio de value.
AllowTrailingWhite Elemento ws al final de value.
AllowLeadingSign Elemento de signo antes de los dígitos.
AllowTrailingSign Elemento de signo después de dígitos.
AllowParentheses Elemento de signo en forma de paréntesis que incluye el valor numérico.
AllowThousands Elemento separador de grupo (,).
AllowCurrencySymbol Elemento currency ($).
Currency Todos los elementos. Sin embargo, value no puede representar un número hexadecimal o un número en notación exponencial.
Float El elemento ws al principio o al final de value, firma al principio de valuey el símbolo decimal (.). El value parámetro también puede usar la notación exponencial.
Number Los elementos ws, sign, group separator (,) y decimal point (.).
Any Todos los elementos. Sin embargo, value no puede representar un número hexadecimal.

Si se usa la NumberStyles.AllowHexSpecifier marca , value debe ser un valor hexadecimal. Las únicas marcas que pueden estar presentes en style son NumberStyles.AllowLeadingWhite y NumberStyles.AllowTrailingWhite. (La NumberStyles enumeración tiene un estilo compuesto, HexNumber, que incluye ambas marcas de espacio en blanco).

El provider parámetro es una IFormatProvider implementación. Su GetFormat método devuelve un NumberFormatInfo objeto que proporciona información específica de la referencia cultural sobre el formato de value. El provider parámetro puede ser cualquiera de los siguientes:

  • Objeto CultureInfo que representa la referencia cultural que proporciona información de formato. Su GetFormat método devuelve el NumberFormatInfo objeto que proporciona información de formato numérico para esa referencia cultural.

  • Objeto NumberFormatInfo que proporciona información de formato numérico. (Su implementación de GetFormat solo devuelve a sí mismo).

  • Objeto personalizado que implementa IFormatProvider. Su GetFormat método crea una instancia de y devuelve el NumberFormatInfo objeto que proporciona información de formato.

Si provider es null, se usa el NumberFormatInfo objeto de la referencia cultural actual.

Consulte también

Se aplica a

TryParse(String, IFormatProvider, BigInteger)

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Intenta analizar una cadena en un valor.

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

Parámetros

s
String

Cadena que se va a analizar.

provider
IFormatProvider

Un objeto que proporciona información de formato específica de la referencia cultural sobre s.

result
BigInteger

Cuando este método vuelve, contiene el resultado de analizar s correctamente o un valor no definido en caso de error.

Devoluciones

true es si s se ha analizado correctamente; en caso contrario, falsees .

Se aplica a

TryParse(ReadOnlySpan<Char>, IFormatProvider, BigInteger)

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Intenta analizar un intervalo de caracteres en un valor.

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

Parámetros

s
ReadOnlySpan<Char>

Intervalo de caracteres que se van a analizar.

provider
IFormatProvider

Un objeto que proporciona información de formato específica de la referencia cultural sobre s.

result
BigInteger

Cuando este método devuelve , contiene el resultado de analizar scorrectamente o un valor indefinido en caso de error.

Devoluciones

true es si s se ha analizado correctamente; en caso contrario, falsees .

Se aplica a

TryParse(String, BigInteger)

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Intenta convertir la representación en forma de cadena de un número en su equivalente BigInteger y devuelve un valor que indica si la conversión tuvo éxito.

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);
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

Representación de cadena de un número.

result
BigInteger

Cuando este método vuelve, contiene el equivalente BigInteger al número contenido en value, o cero (0) si se produce un error en la conversión. Se produce un error en la conversión si el parámetro value es null o no tiene el formato correcto. Este parámetro se pasa sin inicializar.

Devoluciones

true si value se convirtió correctamente; en caso contrario, false.

Excepciones

value es null.

Ejemplos

En el ejemplo siguiente se usa el TryParse(String, BigInteger) método para crear una instancia de dos BigInteger objetos. Si las conversiones se realizan correctamente, multiplica cada objeto por otro número y, a continuación, llama al Compare método para determinar la relación entre los dos 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.
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.

Comentarios

El TryParse(String, BigInteger) método es similar al Parse(String) método , salvo que no produce una excepción si se produce un error en la conversión. Este método elimina la necesidad de usar el control de excepciones para probar si FormatExceptionvalue no es válido y no se puede analizar correctamente.

El value parámetro debe ser la representación de cadena de un número decimal con el formato siguiente:

[ws] [sign] digits[ws]

Los elementos de los corchetes ([ y ]) son opcionales. En esta tabla se describe cada elemento.

Elemento Descripción
ws Espacio en blanco opcional.
sign Un signo opcional. Los caracteres de signo válidos se determinan mediante las NumberFormatInfo.NegativeSign propiedades y NumberFormatInfo.PositiveSign de la referencia cultural actual.
dígitos Secuencia de dígitos decimales comprendidos entre 0 y 9.

Nota

La cadena especificada por el value parámetro no puede contener ningún separador de grupo ni separador decimal, y no puede tener una parte decimal.

El value parámetro se interpreta mediante el NumberStyles.Integer estilo . Además de los dígitos decimales, solo se permiten espacios iniciales y finales con un signo inicial. Para definir explícitamente los elementos de estilo con la información de formato específica de la referencia cultural que puede estar presente en value, llame al TryParse(String, NumberStyles, IFormatProvider, BigInteger) método .

El value parámetro se analiza mediante la información de formato de un NumberFormatInfo objeto para la referencia cultural actual. Para obtener más información, vea NumberFormatInfo.CurrentInfo.

Esta sobrecarga interpreta todos los dígitos del value parámetro como dígitos decimales. Para analizar la representación de cadena de un número hexadecimal, llame a la TryParse(String, NumberStyles, IFormatProvider, BigInteger) sobrecarga en su lugar.

Consulte también

Se aplica a

TryParse(ReadOnlySpan<Char>, BigInteger)

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Intenta convertir la representación de un número incluido en el intervalo de caracteres de solo lectura especificado en su equivalente BigInteger y devuelve un valor que indica si la conversión se ha realizado correctamente.

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>

Representación de un número como un intervalo de solo lectura de caracteres.

result
BigInteger

Cuando este método vuelve, contiene el equivalente BigInteger al número contenido en value, o cero (0) si se produce un error en la conversión. Se produce un error de conversión si el parámetro value es un intervalo de caracteres vacío o no tiene el formato correcto. Este parámetro se pasa sin inicializar.

Devoluciones

true si value se convirtió correctamente; en caso contrario, false.

Consulte también

Se aplica a

TryParse(String, NumberStyles, IFormatProvider, BigInteger)

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Intenta convertir la representación de cadena de un número con un estilo específico y un formato específico de la referencia cultural en su equivalente de BigInteger y devuelve un valor que indica si la conversión fue correcta.

public:
 static bool TryParse(System::String ^ value, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result);
public:
 static bool TryParse(System::String ^ value, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result) = System::Numerics::INumberBase<System::Numerics::BigInteger>::TryParse;
public static bool TryParse (string value, System.Globalization.NumberStyles style, IFormatProvider provider, 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

Representación de cadena de un número. La cadena se interpreta usando el estilo especificado por style.

style
NumberStyles

Combinación bit a bit de los valores de enumeración que indica los elementos de estilo que pueden estar presentes en value. Un valor que se especifica de forma habitual es Integer.

provider
IFormatProvider

Objeto que proporciona información de formato específica de la referencia cultural acerca de value.

result
BigInteger

Cuando este método vuelve, contiene el equivalente BigInteger al número contenido en value, o Zero si se produjo un error en la conversión. Se produce un error en la conversión si el parámetro value es null o no tiene un formato conforme a style. Este parámetro se pasa sin inicializar.

Devoluciones

true si el parámetro value se convierte correctamente; en caso contrario, false.

Excepciones

style no es un valor NumberStyles.

o bien

style incluye la marca AllowHexSpecifier o HexNumber junto con otro valor.

Ejemplos

En el ejemplo siguiente se realizan algunas llamadas al TryParse(String, NumberStyles, IFormatProvider, BigInteger) método mediante varias combinaciones de valores para los style parámetros y 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.
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.

Una serie de llamadas individuales al TryParse(String, NumberStyles, IFormatProvider, BigInteger) método pasan una instancia de la siguiente BigIntegerFormatProvider clase, que define una tilde (~) como el signo 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;
      }
   }
}
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

Comentarios

El TryParse(String, NumberStyles, IFormatProvider, BigInteger) método es similar al Parse(String, NumberStyles, IFormatProvider) método , salvo que no produce una excepción si se produce un error en la conversión. Este método elimina la necesidad de usar el control de excepciones para probar si FormatExceptionvalue no es válido y no se puede analizar correctamente.

El style parámetro define los elementos de estilo (como el espacio en blanco o un signo positivo o negativo) que se permiten en el value parámetro para que la operación de análisis se realice correctamente. Debe ser una combinación de marcas de bits de la NumberStyles enumeración. Según el valor de style, el value parámetro puede incluir los siguientes elementos:

[ws] [$][sign][digits,]digits[.fractional_digits][E[sign]exponential_digits][ws]

Si el style parámetro incluye AllowHexSpecifier, el value parámetro puede incluir los siguientes elementos:

[ws] hexdigits[ws]

Los elementos de los corchetes ([ y ]) son opcionales. En esta tabla se describe cada elemento.

Elemento Descripción
ws Espacio en blanco opcional. El espacio en blanco puede aparecer al principio de value si incluye la NumberStyles.AllowLeadingWhite marca o al final de value si style incluye la NumberStyles.AllowTrailingWhite marca .style
$ Símbolo de moneda específico de la referencia cultural. Su posición en la cadena se define mediante la CurrencyPositivePattern propiedad del NumberFormatInfo objeto devuelto por el GetFormat método del provider parámetro . El símbolo de moneda puede aparecer en value si style incluye la NumberStyles.AllowCurrencySymbol marca .
sign Un signo opcional. El signo puede aparecer al principio de value si incluye la NumberStyles.AllowLeadingSign marca y puede aparecer al final de value si style incluye la NumberStyles.AllowTrailingSignstyle marca. Los paréntesis se pueden usar en value para indicar un valor negativo si style incluye la NumberStyles.AllowParentheses marca .
dígitos Secuencia de dígitos de 0 a 9.
, Separador de grupo específico de la referencia cultural. El separador de grupo de la referencia cultural especificada por provider puede aparecer en value si style incluye la NumberStyles.AllowThousands marca .
. Símbolo de separador decimal específico de la referencia cultural. El símbolo de separador decimal de la referencia cultural especificada por provider puede aparecer en value si style incluye la NumberStyles.AllowDecimalPoint marca .
fractional_digits Una o varias apariciones del dígito 0. Los dígitos fraccionarios solo pueden aparecer en value si style incluye la NumberStyles.AllowDecimalPoint marca .
E El carácter "e" o "E", que indica que el valor se representa en notación exponencial (científica). El value parámetro puede representar un número en notación exponencial si style incluye la NumberStyles.AllowExponent marca .
exponential_digits Secuencia de dígitos de 0 a 9. El value parámetro puede representar un número en notación exponencial si style incluye la NumberStyles.AllowExponent marca .
hexdigits Secuencia de dígitos hexadecimales de 0 a f, o de 0 a F.

Nota

La operación de análisis omite los caracteres NUL (U+0000) terminados, s independientemente del valor del style argumento.

Una cadena con dígitos decimales solo (que corresponde a la NumberStyles.None marca) siempre analiza correctamente. La mayoría de los miembros restantes NumberStyles controlan los elementos que pueden estar presentes, pero no deben estar presentes, en esta cadena de entrada. En la tabla siguiente se indica cómo afectan los miembros individuales NumberStyles a los elementos que pueden estar presentes en value.

Valores no compuestos NumberStyles Elementos permitidos en el valor además de dígitos
None Solo dígitos decimales.
AllowDecimalPoint Los elementos decimales (.) y fractional_digits . Sin embargo, fractional_digits solo debe constar de uno o más dígitos, o el método devuelve false.
AllowExponent Carácter "e" o "E", que indica la notación exponencial, junto con exponential_digits. Si value representa un número en notación exponencial, no puede tener un componente fraccionaria distinto de cero.
AllowLeadingWhite Elemento ws al principio de value.
AllowTrailingWhite Elemento ws al final de value.
AllowLeadingSign Elemento de signo antes de los dígitos.
AllowTrailingSign Elemento de signo después de dígitos.
AllowParentheses Elemento de signo en forma de paréntesis que incluye el valor numérico.
AllowThousands Elemento separador de grupo (,).
AllowCurrencySymbol Elemento currency ($).
Currency Todos los elementos. Sin embargo, value no puede representar un número hexadecimal o un número en notación exponencial.
Float El elemento ws al principio o al final de value, firma al principio de valuey el símbolo decimal (.). El value parámetro también puede usar la notación exponencial.
Number Los elementos ws, sign, group separator (,) y decimal point (.).
Any Todos los elementos. Sin embargo, value no puede representar un número hexadecimal.

Importante

Si usa el TryParse método para realizar un recorrido de ida y vuelta la representación de cadena de un BigInteger valor generado por el ToString método , debe usar el BigInteger.ToString(String) método con el especificador de formato "R" para generar la representación de cadena del BigInteger valor. De lo contrario, la representación de cadena de BigInteger conserva solo los 50 dígitos más significativos del valor original y los datos se pueden perder cuando se usa el TryParse método para restaurar el BigInteger valor.

Si se usa la NumberStyles.AllowHexSpecifier marca , value debe ser un valor hexadecimal. Las únicas marcas que pueden estar presentes en style son NumberStyles.AllowLeadingWhite y NumberStyles.AllowTrailingWhite. (La NumberStyles enumeración tiene un estilo compuesto, HexNumber, que incluye ambas marcas de espacio en blanco).

Nota

Si value es la representación de cadena de un número hexadecimal, no puede ir precedida de ninguna decoración (como 0x o &h) que la diferencie como un número hexadecimal. Esto hace que se produzca un error en la conversión.

Si value es una cadena hexadecimal, el TryParse(String, NumberStyles, IFormatProvider, BigInteger) método interpreta value como un número negativo almacenado mediante la representación complementaria de dos si sus dos primeros dígitos hexadecimales son mayores o iguales que 0x80. En otras palabras, el método interpreta el bit de orden más alto del primer byte de value como bit de signo. Para asegurarse de que una cadena hexadecimal se interpreta correctamente como un número positivo, el primer dígito de value debe tener un valor de cero. Por ejemplo, el método interpreta 0x80 como un valor negativo, pero interpreta o 0x0800x0080 como un valor positivo. En el ejemplo siguiente se muestra la diferencia entre las cadenas hexadecimales que representan valores negativos y 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.
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.

El provider parámetro es una IFormatProvider implementación. Su GetFormat método devuelve un NumberFormatInfo objeto que proporciona información específica de la referencia cultural sobre el formato de value. El provider parámetro puede ser cualquiera de los siguientes:

  • Objeto CultureInfo que representa la referencia cultural que proporciona información de formato. Su GetFormat método devuelve el NumberFormatInfo objeto que proporciona información de formato numérico para esa referencia cultural.

  • Objeto NumberFormatInfo que proporciona información de formato numérico. (Su implementación de GetFormat solo devuelve a sí mismo).

  • Objeto personalizado que implementa IFormatProvider. Su GetFormat método crea una instancia de y devuelve el NumberFormatInfo objeto que proporciona información de formato.

Si provider es null, se usa el NumberFormatInfo objeto de la referencia cultural actual.

Consulte también

Se aplica a