UInt32.TryParse Método

Definición

Intenta convertir la representación de cadena de un número en el entero de 32 bits sin signo equivalente. Un valor devuelto indica si la conversión se realizó correctamente o si se produjeron errores.

Sobrecargas

TryParse(ReadOnlySpan<Byte>, IFormatProvider, UInt32)

Intenta analizar un intervalo de caracteres UTF-8 en un valor.

TryParse(ReadOnlySpan<Char>, UInt32)

Intenta convertir la representación de intervalo de un número en el entero sin signo de 32 bits equivalente. Un valor devuelto indica si la conversión se realizó correctamente o si se produjeron errores.

TryParse(String, UInt32)

Intenta convertir la representación de cadena de un número en el entero de 32 bits sin signo equivalente. Un valor devuelto indica si la conversión se realizó correctamente o si se produjeron errores.

TryParse(ReadOnlySpan<Char>, IFormatProvider, UInt32)

Intenta analizar un intervalo de caracteres en un valor.

TryParse(String, IFormatProvider, UInt32)

Intenta analizar una cadena en un valor.

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

Intenta analizar un intervalo de caracteres UTF-8 en un valor.

TryParse(ReadOnlySpan<Byte>, UInt32)

Intenta convertir un intervalo de caracteres UTF-8 que contiene la representación de cadena de un número en su entero de 32 bits sin signo equivalente.

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

Intenta convertir la representación de intervalo de un número en el estilo y el formato específicos de la referencia cultural que se hayan especificado en el entero sin signo de 32 bits equivalente. Un valor devuelto indica si la conversión se realizó correctamente o si se produjeron errores.

TryParse(String, NumberStyles, IFormatProvider, UInt32)

Intenta convertir la representación de cadena de un número en el estilo y en el formato específicos de la referencia cultural que se hayan indicado en el entero de 32 bits sin signo equivalente. Un valor devuelto indica si la conversión se realizó correctamente o si se produjeron errores.

TryParse(ReadOnlySpan<Byte>, IFormatProvider, UInt32)

Intenta analizar un intervalo de caracteres UTF-8 en un valor.

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

Parámetros

utf8Text
ReadOnlySpan<Byte>

Intervalo de caracteres UTF-8 que se van a analizar.

provider
IFormatProvider

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

result
UInt32

En la devolución, contiene el resultado del análisis utf8Text correcto o de un valor no definido en caso de error.

Devoluciones

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

Se aplica a

TryParse(ReadOnlySpan<Char>, UInt32)

Importante

Esta API no es conforme a CLS.

Intenta convertir la representación de intervalo de un número en el entero sin signo de 32 bits equivalente. Un valor devuelto indica si la conversión se realizó correctamente o si se produjeron errores.

public:
 static bool TryParse(ReadOnlySpan<char> s, [Runtime::InteropServices::Out] System::UInt32 % result);
public static bool TryParse (ReadOnlySpan<char> s, out uint result);
[System.CLSCompliant(false)]
public static bool TryParse (ReadOnlySpan<char> s, out uint result);
static member TryParse : ReadOnlySpan<char> * uint32 -> bool
[<System.CLSCompliant(false)>]
static member TryParse : ReadOnlySpan<char> * uint32 -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), ByRef result As UInteger) As Boolean

Parámetros

s
ReadOnlySpan<Char>

Un intervalo que contiene los caracteres que representan el número que se va a convertir.

result
UInt32

El resultado que devuelve este método contiene el valor entero sin signo de 32 bits que es equivalente al número contenido en s si la conversión se realizó correctamente, o bien, cero si no se realizó correctamente. Se produce un error en la conversión si el s parámetro es null o Empty, no tiene el formato correcto o representa un número menor que UInt32.MinValue o mayor que UInt32.MaxValue. Este parámetro se pasa sin inicializar; cualquier valor proporcionado originalmente en result se sobrescribirá.

Devoluciones

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

Atributos

Se aplica a

TryParse(String, UInt32)

Importante

Esta API no es conforme a CLS.

Alternativa conforme a CLS
System.Int64.TryParse(String, Int64)

Intenta convertir la representación de cadena de un número en el entero de 32 bits sin signo equivalente. Un valor devuelto indica si la conversión se realizó correctamente o si se produjeron errores.

public:
 static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] System::UInt32 % result);
[System.CLSCompliant(false)]
public static bool TryParse (string s, out uint result);
public static bool TryParse (string? s, out uint result);
[System.CLSCompliant(false)]
public static bool TryParse (string? s, out uint result);
[<System.CLSCompliant(false)>]
static member TryParse : string * uint32 -> bool
static member TryParse : string * uint32 -> bool
Public Shared Function TryParse (s As String, ByRef result As UInteger) As Boolean

Parámetros

s
String

Una cadena que representa el número que se va a convertir.

result
UInt32

El resultado que devuelve este método contiene el valor entero sin signo de 32 bits que es equivalente al número contenido en s si la conversión se realizó correctamente, o bien, cero si no se realizó correctamente. Se produce un error en la conversión si el s parámetro es null o Empty, no tiene el formato correcto o representa un número menor que UInt32.MinValue o mayor que UInt32.MaxValue. Este parámetro se pasa sin inicializar; cualquier valor proporcionado originalmente en result se sobrescribirá.

Devoluciones

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

Atributos

Ejemplos

En el ejemplo siguiente se llama al TryParse(String, UInt32) método una vez para cada elemento de una matriz de cadenas.

string[] numericStrings = { "1293.8", "+1671.7", "28347.",  
                            "   33113684  ", "(0)", "-0", "-1", 
                            "+1293617", "18-", "119870", "31,024", 
                            "  3127094 ", "00700000" };
uint number;
foreach (string numericString in numericStrings)
{
   if (UInt32.TryParse(numericString, out number)) 
      Console.WriteLine("Converted '{0}' to {1}.", numericString, number);
   else
      Console.WriteLine("Cannot convert '{0}' to a UInt32.", numericString);
}
// The example displays the following output:
//       Cannot convert '1293.8' to a UInt32.
//       Cannot convert '+1671.7' to a UInt32.
//       Cannot convert '28347.' to a UInt32.
//       Converted '   33113684  ' to 33113684.
//       Cannot convert '(0)' to a UInt32.
//       Converted '-0' to 0.
//       Cannot convert '-1' to a UInt32.
//       Converted '+1293617' to 1293617.
//       Cannot convert '18-' to a UInt32.
//       Converted '119870' to 119870.
//       Cannot convert '31,024' to a UInt32.
//       Converted '  3127094 ' to 3127094.
//       Converted '0070000' to 70000.
let numericStrings = 
    [| "1293.8"; "+1671.7"; "28347."
       "   33113684  "; "(0)"; "-0"; "-1" 
       "+1293617"; "18-"; "119870"; "31,024" 
       "  3127094 "; "00700000" |]

for numericString in numericStrings do
    match UInt32.TryParse numericString with
    | true, number ->
        printfn $"Converted '{numericString}' to {number}."
    | _ ->
        printfn $"Cannot convert '{numericString}' to a UInt32."
// The example displays the following output:
//       Cannot convert '1293.8' to a UInt32.
//       Cannot convert '+1671.7' to a UInt32.
//       Cannot convert '28347.' to a UInt32.
//       Converted '   33113684  ' to 33113684.
//       Cannot convert '(0)' to a UInt32.
//       Converted '-0' to 0.
//       Cannot convert '-1' to a UInt32.
//       Converted '+1293617' to 1293617.
//       Cannot convert '18-' to a UInt32.
//       Converted '119870' to 119870.
//       Cannot convert '31,024' to a UInt32.
//       Converted '  3127094 ' to 3127094.
//       Converted '0070000' to 70000.
Dim numericStrings() As String = {"1293.8", "+1671.7", "28347.", 
                                  "   33113684  ", "(0)", "-0", "-1",
                                  "+1293617", "18-", "119870", 
                                  "31,024", "  3127094 ", "0070000" }
Dim number As UInteger
For Each numericString As String In numericStrings
   If UInt32.TryParse(numericString, number) Then
      Console.WriteLine("Converted '{0}' to {1}.", numericString, number)
   Else
      Console.WriteLine("Cannot convert '{0}' to a UInt32.", numericString)
   End If      
Next
' The example displays the following output:
'       Cannot convert '1293.8' to a UInt32.
'       Cannot convert '+1671.7' to a UInt32.
'       Cannot convert '28347.' to a UInt32.
'       Converted '   33113684  ' to 33113684.
'       Cannot convert '(0)' to a UInt32.
'       Converted '-0' to 0.
'       Cannot convert '-1' to a UInt32.
'       Converted '+1293617' to 1293617.
'       Cannot convert '18-' to a UInt32.
'       Converted '119870' to 119870.
'       Cannot convert '31,024' to a UInt32.
'       Converted '  3127094 ' to 3127094.
'       Converted '0070000' to 70000.

Comentarios

El TryParse método es similar al Parse 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 FormatExceptions no es válido y no se puede analizar correctamente.

El s parámetro debe ser la representación de cadena de un número decimal de la forma 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 que van de 0 a 9.

El s 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 s, llame al TryParse(String, NumberStyles, IFormatProvider, UInt32) método .

Nota

La cadena especificada por el s parámetro no puede contener separadores de grupo ni separadores decimales, y no puede tener una parte fraccionaria.

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

Esta sobrecarga interpreta todos los dígitos del s 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, UInt32) sobrecarga en su lugar.

Consulte también

Se aplica a

TryParse(ReadOnlySpan<Char>, IFormatProvider, UInt32)

Intenta analizar un intervalo de caracteres en un valor.

public:
 static bool TryParse(ReadOnlySpan<char> s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::UInt32 % result) = ISpanParsable<System::UInt32>::TryParse;
public static bool TryParse (ReadOnlySpan<char> s, IFormatProvider? provider, out uint result);
static member TryParse : ReadOnlySpan<char> * IFormatProvider * uint32 -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), provider As IFormatProvider, ByRef result As UInteger) 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
UInt32

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, IFormatProvider, UInt32)

Intenta analizar una cadena en un valor.

public:
 static bool TryParse(System::String ^ s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::UInt32 % result) = IParsable<System::UInt32>::TryParse;
public static bool TryParse (string? s, IFormatProvider? provider, out uint result);
static member TryParse : string * IFormatProvider * uint32 -> bool
Public Shared Function TryParse (s As String, provider As IFormatProvider, ByRef result As UInteger) 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
UInt32

Cuando este método vuelve, contiene el resultado del análisis s correcto o de un valor indefinido en caso de error.

Devoluciones

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

Se aplica a

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

Intenta analizar un intervalo de caracteres UTF-8 en un valor.

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

Parámetros

utf8Text
ReadOnlySpan<Byte>

Intervalo de caracteres UTF-8 que se van a analizar.

style
NumberStyles

Combinación bit a bit de estilos de número que pueden estar presentes en utf8Text.

provider
IFormatProvider

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

result
UInt32

En la devolución, contiene el resultado del análisis utf8Text correcto o de un valor no definido en caso de error.

Devoluciones

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

Se aplica a

TryParse(ReadOnlySpan<Byte>, UInt32)

Intenta convertir un intervalo de caracteres UTF-8 que contiene la representación de cadena de un número en su entero de 32 bits sin signo equivalente.

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

Parámetros

utf8Text
ReadOnlySpan<Byte>

Intervalo que contiene los caracteres UTF-8 que representan el número que se va a convertir.

result
UInt32

Cuando este método devuelve , contiene el valor entero sin signo de 32 bits equivalente al número contenido en utf8Text si la conversión se realizó correctamente o cero si se produjo un error en la conversión. Este parámetro se pasa sin inicializar; se sobrescribirán todos los valores proporcionados originalmente en el resultado.

Devoluciones

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

Se aplica a

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

Importante

Esta API no es conforme a CLS.

Intenta convertir la representación de intervalo de un número en el estilo y el formato específicos de la referencia cultural que se hayan especificado en el entero sin signo de 32 bits equivalente. Un valor devuelto indica si la conversión se realizó correctamente o si se produjeron errores.

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

Parámetros

s
ReadOnlySpan<Char>

Un intervalo que contiene los caracteres que representan el número que se va a convertir. El intervalo se interpreta mediante el estilo especificado por el parámetro style.

style
NumberStyles

Combinación bit a bit de valores de enumeración que indica el formato permitido de s. 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 s.

result
UInt32

El resultado que devuelve este método contiene el valor entero sin signo de 32 bits equivalente al número contenido en s si la conversión se realizó correctamente, o bien, cero si no se realizó correctamente. Se produce un error en la conversión si el s parámetro es null o Empty, no está en un formato compatible con styleo representa un número menor que UInt32.MinValue o mayor que UInt32.MaxValue. Este parámetro se pasa sin inicializar; cualquier valor proporcionado originalmente en result se sobrescribirá.

Devoluciones

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

Atributos

Se aplica a

TryParse(String, NumberStyles, IFormatProvider, UInt32)

Importante

Esta API no es conforme a CLS.

Alternativa conforme a CLS
System.Int64.TryParse(String, Int64)

Intenta convertir la representación de cadena de un número en el estilo y en el formato específicos de la referencia cultural que se hayan indicado en el entero de 32 bits sin signo equivalente. Un valor devuelto indica si la conversión se realizó correctamente o si se produjeron errores.

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

Parámetros

s
String

Una cadena que representa el número que se va a convertir. La cadena se interpreta usando el estilo especificado por el parámetro style.

style
NumberStyles

Combinación bit a bit de valores de enumeración que indica el formato permitido de s. 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 s.

result
UInt32

El resultado que devuelve este método contiene el valor entero sin signo de 32 bits equivalente al número contenido en s si la conversión se realizó correctamente, o bien, cero si no se realizó correctamente. Se produce un error en la conversión si el s parámetro es null o Empty, no está en un formato compatible con styleo representa un número menor que UInt32.MinValue o mayor que UInt32.MaxValue. Este parámetro se pasa sin inicializar; cualquier valor proporcionado originalmente en result se sobrescribirá.

Devoluciones

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

Atributos

Excepciones

style no es un valor NumberStyles.

o bien

style no es una combinación de valores AllowHexSpecifier y HexNumber.

Ejemplos

En el ejemplo siguiente se llama al TryParse(String, NumberStyles, IFormatProvider, UInt32) método con una serie de cadenas y NumberStyles valores diferentes.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string numericString;
      NumberStyles styles;
      
      numericString = "2106034";
      styles = NumberStyles.Integer;
      CallTryParse(numericString, styles);
      
      numericString = "-10603";
      styles = NumberStyles.None;
      CallTryParse(numericString, styles);
      
      numericString = "29103674.00";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(numericString, styles);
      
      numericString = "10345.72";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "41792210E-01";
      styles = NumberStyles.Integer | NumberStyles.AllowExponent;
      CallTryParse(numericString, styles); 
      
      numericString = "9112E-01";
      CallTryParse(numericString, styles);
          
      numericString = "312E01";
      CallTryParse(numericString, styles); 
      
      numericString = "FFC86DA1";
      CallTryParse(numericString, NumberStyles.HexNumber);
      
      numericString = "0x8F8C";
      CallTryParse(numericString, NumberStyles.HexNumber);
   }
   
   private static void CallTryParse(string stringToConvert, NumberStyles styles)
   {
      uint number;
      bool result = UInt32.TryParse(stringToConvert, styles, 
                                   CultureInfo.InvariantCulture, out number);
      if (result)
         Console.WriteLine($"Converted '{stringToConvert}' to {number}.");
      else
         Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed.");
   }
}
// The example displays the following output:
//       Converted '2106034' to 2106034.
//       Attempted conversion of '-10603' failed.
//       Converted '29103674.00' to 29103674.
//       Attempted conversion of '10345.72' failed.
//       Converted '41792210E-01' to 4179221.
//       Attempted conversion of '9112E-01' failed.
//       Converted '312E01' to 3120.
//       Converted 'FFC86DA1' to 4291325345.
//       Attempted conversion of '0x8F8C' failed.
open System
open System.Globalization

let callTryParse (stringToConvert: string) (styles: NumberStyles) =
    match UInt32.TryParse(stringToConvert, styles, CultureInfo.InvariantCulture) with
    | true, number ->
        printfn $"Converted '{stringToConvert}' to {number}."
        printfn $"Attempted conversion of '{stringToConvert}' failed."
    | _ -> ()

do
    let numericString = "2106034"
    let styles = NumberStyles.Integer
    callTryParse numericString styles

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

    let numericString = "29103674.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 = "41792210E-01"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowExponent
    callTryParse numericString styles 

    let numericString = "9112E-01"
    callTryParse numericString styles
        
    let numericString = "312E01"
    callTryParse numericString styles 

    let numericString = "FFC86DA1"
    callTryParse numericString NumberStyles.HexNumber

    let numericString = "0x8F8C"
    callTryParse numericString NumberStyles.HexNumber
   
// The example displays the following output:
//       Converted '2106034' to 2106034.
//       Attempted conversion of '-10603' failed.
//       Converted '29103674.00' to 29103674.
//       Attempted conversion of '10345.72' failed.
//       Converted '41792210E-01' to 4179221.
//       Attempted conversion of '9112E-01' failed.
//       Converted '312E01' to 3120.
//       Converted 'FFC86DA1' to 4291325345.
//       Attempted conversion of '0x8F8C' failed.
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim numericString As String
      Dim styles As NumberStyles
      
      numericString = "2106034"
      styles = NumberStyles.Integer
      CallTryParse(numericString, styles)
      
      numericString = "-10603"
      styles = NumberStyles.None
      CallTryParse(numericString, styles)
      
      numericString = "29103674.00"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(numericString, styles)
      
      numericString = "10345.72"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(numericString, styles)

      numericString = "41792210E-01"
      styles = NumberStyles.Integer Or NumberStyles.AllowExponent
      CallTryParse(numericString, styles) 
      
      numericString = "9112E-01"
      CallTryParse(numericString, styles)
          
      numericString = "312E01"
      CallTryParse(numericString, styles) 
      
      numericString = "FFC86DA1"
      CallTryParse(numericString, NumberStyles.HexNumber)
      
      numericString = "0x8F8C"
      CallTryParse(numericString, NumberStyles.HexNumber)
   End Sub
   
   Private Sub CallTryParse(stringToConvert As String, styles AS NumberStyles)
      Dim number As UInteger
      Dim result As Boolean = UInt32.TryParse(stringToConvert, styles, _
                                              CultureInfo.InvariantCulture, 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 '2106034' to 2106034.
'       Attempted conversion of '-10603' failed.
'       Converted '29103674.00' to 29103674.
'       Attempted conversion of '10345.72' failed.
'       Converted '41792210E-01' to 4179221.
'       Attempted conversion of '9112E-01' failed.
'       Converted '312E01' to 3120.
'       Converted 'FFC86DA1' to 4291325345.
'       Attempted conversion of '0x8F8C' failed.

Comentarios

El TryParse(String, NumberStyles, IFormatProvider, UInt32) 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 FormatExceptions 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 s 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 s parámetro puede incluir los siguientes elementos:

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

Los elementos entre corchetes ([ y ]) son opcionales. O bien, si el style parámetro incluye NumberStyles.AllowHexSpecifier, el s parámetro puede incluir los siguientes elementos:

[ws] hexdigits[ws]

En esta tabla se describe cada elemento.

Elemento Descripción
ws Espacio en blanco opcional. El espacio en blanco puede aparecer al principio de s si incluye la NumberStyles.AllowLeadingWhite marca o al final de s 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 s si style incluye la NumberStyles.AllowCurrencySymbol marca .
sign Un signo opcional. El signo puede aparecer al principio de s si incluye la NumberStyles.AllowLeadingSign marca y puede aparecer al final de s si style incluye la NumberStyles.AllowTrailingSignstyle marca. Los paréntesis se pueden usar en s para indicar un valor negativo si style incluye la NumberStyles.AllowParentheses marca . Sin embargo, si el signo negativo está presente, s solo puede representar el valor cero para que la operación de análisis se realice correctamente.
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 s 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 s 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 s 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 s 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 s 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 0 a F.

Nota

La operación de análisis omite todos los caracteres NUL (U+0000) de 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 son necesarios para 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 s.

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 debe constar de solo uno o más 0 dígitos, o el método devuelve false.
AllowExponent El carácter "e" o "E", que indica la notación exponencial, junto con exponential_digits. Si s representa un número en notación exponencial, no puede tener un componente fraccionaria distinto de cero.
AllowLeadingWhite Elemento ws al principio de s.
AllowTrailingWhite Elemento ws al final de s.
AllowLeadingSign Elemento de signo antes de los dígitos.
AllowTrailingSign Elemento sign después de dígitos.
AllowParentheses Elemento de signo en forma de paréntesis que incluye un valor numérico cero.
AllowThousands Elemento separador de grupo (,).
AllowCurrencySymbol Elemento currency ($).
Currency Todos los elementos. Sin embargo, s 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 s, firma al principio de sy el símbolo de separador decimal (.). El s 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, s no puede representar un número hexadecimal.

Si se usa la NumberStyles.AllowHexSpecifier marca , s 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 s 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.

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 s. 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