UInt32.Parse Método

Definición

Convierte la representación en forma de cadena de un número en el entero de 32 bits sin signo equivalente.

Sobrecargas

Parse(String, NumberStyles, IFormatProvider)

Convierte la representación en forma de cadena de un número con el estilo y el formato específicos de la referencia cultural que se hayan especificado en el entero de 32 bits sin signo equivalente.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Convierte la representación de intervalo de un número con el estilo y el formato específicos de la referencia cultural que se hayan especificado en el entero sin signo de 32 bits equivalente.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Analiza un intervalo de caracteres UTF-8 en un valor.

Parse(String, IFormatProvider)

Convierte la representación en forma de cadena de un número con el formato específico de la referencia cultural que se haya especificado en el entero de 32 bits sin signo equivalente.

Parse(String, NumberStyles)

Convierte la representación en forma de cadena de un número del estilo especificado en el entero de 32 bits sin signo equivalente.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Analiza un intervalo de caracteres en un valor.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Analiza un intervalo de caracteres UTF-8 en un valor.

Parse(String)

Convierte la representación en forma de cadena de un número en el entero de 32 bits sin signo equivalente.

Parse(String, NumberStyles, IFormatProvider)

Source:
UInt32.cs
Source:
UInt32.cs
Source:
UInt32.cs

Importante

Esta API no es conforme a CLS.

Alternativa conforme a CLS
System.Int64.Parse(String)

Convierte la representación en forma de cadena de un número con el estilo y el formato específicos de la referencia cultural que se hayan especificado en el entero de 32 bits sin signo equivalente.

public:
 static System::UInt32 Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
 static System::UInt32 Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<System::UInt32>::Parse;
[System.CLSCompliant(false)]
public static uint Parse (string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static uint Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static uint Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> uint32
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> uint32
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As UInteger

Parámetros

s
String

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 los valores de enumeración que indica los elementos de estilo que pueden estar presentes en 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.

Devoluciones

Entero sin signo de 32 bits equivalente al número especificado en s.

Implementaciones

Atributos

Excepciones

style no es un valor NumberStyles.

o bien

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

s no está en un formato compatible con style.

s representa un número menor que UInt32.MinValue o mayor que UInt32.MaxValue.

o bien

s incluye dígitos fraccionarios distintos de cero.

Ejemplos

En el ejemplo siguiente se usa el Parse(String, NumberStyles, IFormatProvider) método para convertir varias representaciones de cadena de números en valores enteros sin signo de 32 bits.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] cultureNames= { "en-US", "fr-FR" };
      NumberStyles[] styles= { NumberStyles.Integer,
                               NumberStyles.Integer | NumberStyles.AllowDecimalPoint };
      string[] values = { "170209", "+170209.0", "+170209,0", "-103214.00",
                                 "-103214,00", "104561.1", "104561,1" };
      
      // Parse strings using each culture
      foreach (string cultureName in cultureNames)
      {
         CultureInfo ci = new CultureInfo(cultureName);
         Console.WriteLine("Parsing strings using the {0} culture", 
                           ci.DisplayName);
         // Use each style.
         foreach (NumberStyles style in styles)
         {
            Console.WriteLine("   Style: {0}", style.ToString());
            // Parse each numeric string.
            foreach (string value in values)
            {
               try {
                  Console.WriteLine("      Converted '{0}' to {1}.", value,
                                    UInt32.Parse(value, style, ci));
               }
               catch (FormatException) {
                  Console.WriteLine("      Unable to parse '{0}'.", value);
               }      
               catch (OverflowException) {
                  Console.WriteLine("      '{0}' is out of range of the UInt32 type.",
                                    value);
               }
            }
         }
      }                                    
   }
}
// The example displays the following output:
//       Parsing strings using the English (United States) culture
//          Style: Integer
//             Converted '170209' to 170209.
//             Unable to parse '+170209.0'.
//             Unable to parse '+170209,0'.
//             Unable to parse '-103214.00'.
//             Unable to parse '-103214,00'.
//             Unable to parse '104561.1'.
//             Unable to parse '104561,1'.
//          Style: Integer, AllowDecimalPoint
//             Converted '170209' to 170209.
//             Converted '+170209.0' to 170209.
//             Unable to parse '+170209,0'.
//             '-103214.00' is out of range of the UInt32 type.
//             Unable to parse '-103214,00'.
//             '104561.1' is out of range of the UInt32 type.
//             Unable to parse '104561,1'.
//       Parsing strings using the French (France) culture
//          Style: Integer
//             Converted '170209' to 170209.
//             Unable to parse '+170209.0'.
//             Unable to parse '+170209,0'.
//             Unable to parse '-103214.00'.
//             Unable to parse '-103214,00'.
//             Unable to parse '104561.1'.
//             Unable to parse '104561,1'.
//          Style: Integer, AllowDecimalPoint
//             Converted '170209' to 170209.
//             Unable to parse '+170209.0'.
//             Converted '+170209,0' to 170209.
//             Unable to parse '-103214.00'.
//             '-103214,00' is out of range of the UInt32 type.
//             Unable to parse '104561.1'.
//             '104561,1' is out of range of the UInt32 type.
open System
open System.Globalization

let cultureNames = [| "en-US"; "fr-FR" |]
let styles = 
    [| NumberStyles.Integer; NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint |]
let values = 
    [| "170209"; "+170209.0"; "+170209,0"; "-103214.00"; "-103214,00"; "104561.1"; "104561,1" |]

// Parse strings using each culture
for cultureName in cultureNames do
    let ci = CultureInfo cultureName
    printfn $"Parsing strings using the {ci.DisplayName} culture"
    // Use each style.
    for style in styles do
        printfn $"   Style: {style}"
        // Parse each numeric string.
        for value in values do
            try
                printfn $"      Converted '{value}' to {UInt32.Parse(value, style, ci)}."
            with
            | :? FormatException ->
                printfn $"      Unable to parse '{value}'."
            | :? OverflowException ->
                printfn $"      '{value}' is out of range of the UInt32 type."
// The example displays the following output:
//       Parsing strings using the English (United States) culture
//          Style: Integer
//             Converted '170209' to 170209.
//             Unable to parse '+170209.0'.
//             Unable to parse '+170209,0'.
//             Unable to parse '-103214.00'.
//             Unable to parse '-103214,00'.
//             Unable to parse '104561.1'.
//             Unable to parse '104561,1'.
//          Style: Integer, AllowDecimalPoint
//             Converted '170209' to 170209.
//             Converted '+170209.0' to 170209.
//             Unable to parse '+170209,0'.
//             '-103214.00' is out of range of the UInt32 type.
//             Unable to parse '-103214,00'.
//             '104561.1' is out of range of the UInt32 type.
//             Unable to parse '104561,1'.
//       Parsing strings using the French (France) culture
//          Style: Integer
//             Converted '170209' to 170209.
//             Unable to parse '+170209.0'.
//             Unable to parse '+170209,0'.
//             Unable to parse '-103214.00'.
//             Unable to parse '-103214,00'.
//             Unable to parse '104561.1'.
//             Unable to parse '104561,1'.
//          Style: Integer, AllowDecimalPoint
//             Converted '170209' to 170209.
//             Unable to parse '+170209.0'.
//             Converted '+170209,0' to 170209.
//             Unable to parse '-103214.00'.
//             '-103214,00' is out of range of the UInt32 type.
//             Unable to parse '104561.1'.
//             '104561,1' is out of range of the UInt32 type.
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim cultureNames() As String = { "en-US", "fr-FR" }
      Dim styles() As NumberStyles = { NumberStyles.Integer, _
                                       NumberStyles.Integer Or NumberStyles.AllowDecimalPoint }
      Dim values() As String = { "170209", "+170209.0", "+170209,0", "-103214.00", _
                                 "-103214,00", "104561.1", "104561,1" }
      
      ' Parse strings using each culture
      For Each cultureName As String In cultureNames
         Dim ci As New CultureInfo(cultureName)
         Console.WriteLine("Parsing strings using the {0} culture", ci.DisplayName)
         ' Use each style.
         For Each style As NumberStyles In styles
            Console.WriteLine("   Style: {0}", style.ToString())
            ' Parse each numeric string.
            For Each value As String In values
               Try
                  Console.WriteLine("      Converted '{0}' to {1}.", value, _
                                    UInt32.Parse(value, style, ci))
               Catch e As FormatException
                  Console.WriteLine("      Unable to parse '{0}'.", value)   
               Catch e As OverflowException
                  Console.WriteLine("      '{0}' is out of range of the UInt32 type.", _
                                    value)         
               End Try
            Next
         Next
      Next                                    
   End Sub
End Module
' The example displays the following output:
'       Parsing strings using the English (United States) culture
'          Style: Integer
'             Converted '170209' to 170209.
'             Unable to parse '+170209.0'.
'             Unable to parse '+170209,0'.
'             Unable to parse '-103214.00'.
'             Unable to parse '-103214,00'.
'             Unable to parse '104561.1'.
'             Unable to parse '104561,1'.
'          Style: Integer, AllowDecimalPoint
'             Converted '170209' to 170209.
'             Converted '+170209.0' to 170209.
'             Unable to parse '+170209,0'.
'             '-103214.00' is out of range of the UInt32 type.
'             Unable to parse '-103214,00'.
'             '104561.1' is out of range of the UInt32 type.
'             Unable to parse '104561,1'.
'       Parsing strings using the French (France) culture
'          Style: Integer
'             Converted '170209' to 170209.
'             Unable to parse '+170209.0'.
'             Unable to parse '+170209,0'.
'             Unable to parse '-103214.00'.
'             Unable to parse '-103214,00'.
'             Unable to parse '104561.1'.
'             Unable to parse '104561,1'.
'          Style: Integer, AllowDecimalPoint
'             Converted '170209' to 170209.
'             Unable to parse '+170209.0'.
'             Converted '+170209,0' to 170209.
'             Unable to parse '-103214.00'.
'             '-103214,00' is out of range of the UInt32 type.
'             Unable to parse '104561.1'.
'             '104561,1' is out of range of the UInt32 type.

Comentarios

El style parámetro define los elementos de estilo (como espacios en blanco o el símbolo de 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[.fractional_digits][E[sign]exponential_digits][ws]

Los elementos de los corchetes ([ y ]) son opcionales. Si style 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 y puede aparecer al final de s si style incluye la NumberStyles.AllowTrailingWhitestyle marca .
$ 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 método produce un OverflowException si s incluye un signo negativo y representa un número distinto de cero). El signo puede aparecer al principio de s si incluye la NumberStyles.AllowLeadingSign marca y puede aparecer el 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 .
dígitos Secuencia de dígitos de 0 a 9.
. Símbolo de separador decimal específico de la referencia cultural. El símbolo decimal de la referencia cultural actual puede aparecer en s si style incluye la NumberStyles.AllowDecimalPoint marca .
fractional_digits Una o varias apariciones del dígito 0-9 si style incluye la NumberStyles.AllowExponent marca, o una o varias apariciones del dígito 0 si no lo hace. Los dígitos fraccionarios solo pueden aparecer en s 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 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 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 al NumberStyles.None estilo) 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 s.

Valores no compuestos NumberStyles Elementos permitidos además s de dígitos
NumberStyles.None Solo dígitos decimales.
NumberStyles.AllowDecimalPoint Los elementos decimales (.) y fractional_digits . Sin embargo, si style no incluye la NumberStyles.AllowExponent marca, fractional_digits debe constar de solo uno o más dígitos; de lo contrario, se produce una OverflowException excepción .
NumberStyles.AllowExponent Carácter "e" o "E", que indica la notación exponencial, junto con exponential_digits.
NumberStyles.AllowLeadingWhite Elemento ws al principio de s.
NumberStyles.AllowTrailingWhite Elemento ws al final de s.
NumberStyles.AllowLeadingSign Signo antes de los dígitos.
NumberStyles.AllowTrailingSign Un signo después de los dígitos.
NumberStyles.AllowParentheses Paréntesis antes y después de los dígitos para indicar un valor negativo.
NumberStyles.AllowThousands Elemento separador de grupo (,).
NumberStyles.AllowCurrencySymbol Elemento currency ($).

Si se usa la NumberStyles.AllowHexSpecifier marca , s debe ser un valor hexadecimal. Los únicos otros marcadores que se pueden combinar con él son NumberStyles.AllowLeadingWhite y NumberStyles.AllowTrailingWhite. (La NumberStyles enumeración incluye un estilo de número compuesto, NumberStyles.HexNumber, que incluye ambas marcas de espacio en blanco).

Nota

Si el s parámetro 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 la operación de análisis produzca una excepción.

El provider parámetro es una IFormatProvider implementación cuyo GetFormat método devuelve un NumberFormatInfo objeto que proporciona información específica de la referencia cultural sobre el formato de s. Hay tres maneras de usar el provider parámetro para proporcionar información de formato personalizada a la operación de análisis:

  • Puede pasar el objeto real NumberFormatInfo que proporciona información de formato. (Su implementación de GetFormat simplemente devuelve a sí mismo).

  • Puede pasar un CultureInfo objeto que especifique la referencia cultural cuyo formato se va a usar. Su NumberFormat propiedad proporciona información de formato.

  • Puede pasar una implementación personalizada IFormatProvider . Su GetFormat método debe crear instancias y devolver 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

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Source:
UInt32.cs
Source:
UInt32.cs
Source:
UInt32.cs

Importante

Esta API no es conforme a CLS.

Convierte la representación de intervalo de un número con el estilo y el formato específicos de la referencia cultural que se hayan especificado en el entero sin signo de 32 bits equivalente.

public static uint Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
[System.CLSCompliant(false)]
public static uint Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider provider = default);
[System.CLSCompliant(false)]
public static uint Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> uint32
[<System.CLSCompliant(false)>]
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> uint32
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As UInteger

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 los valores de enumeración que indica los elementos de estilo que pueden estar presentes en 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.

Devoluciones

Entero sin signo de 32 bits equivalente al número especificado en s.

Implementaciones

Atributos

Se aplica a

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Source:
UInt32.cs
Source:
UInt32.cs

Analiza un intervalo de caracteres UTF-8 en un valor.

public static uint Parse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> uint32
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As UInteger

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.

Devoluciones

Resultado del análisis utf8Textde .

Implementaciones

Se aplica a

Parse(String, IFormatProvider)

Source:
UInt32.cs
Source:
UInt32.cs
Source:
UInt32.cs

Importante

Esta API no es conforme a CLS.

Alternativa conforme a CLS
System.Int64.Parse(String)

Convierte la representación en forma de cadena de un número con el formato específico de la referencia cultural que se haya especificado en el entero de 32 bits sin signo equivalente.

public:
 static System::UInt32 Parse(System::String ^ s, IFormatProvider ^ provider);
public:
 static System::UInt32 Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<System::UInt32>::Parse;
[System.CLSCompliant(false)]
public static uint Parse (string s, IFormatProvider provider);
public static uint Parse (string s, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static uint Parse (string s, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * IFormatProvider -> uint32
static member Parse : string * IFormatProvider -> uint32
Public Shared Function Parse (s As String, provider As IFormatProvider) As UInteger

Parámetros

s
String

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

provider
IFormatProvider

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

Devoluciones

Entero sin signo de 32 bits equivalente al número especificado en s.

Implementaciones

Atributos

Excepciones

s no tiene el estilo correcto.

s representa un número menor que UInt32.MinValue o mayor que UInt32.MaxValue.

Ejemplos

En el ejemplo siguiente se muestra el controlador de eventos click de un formulario web. Usa la matriz devuelta por la HttpRequest.UserLanguages propiedad para determinar la configuración regional del usuario. A continuación, crea una instancia de un CultureInfo objeto que corresponde a esa configuración regional. Después NumberFormatInfo , el objeto que pertenece a ese CultureInfo objeto se pasa al Parse(String, IFormatProvider) método para convertir la entrada del usuario en un UInt32 valor.

protected void OkToUInteger_Click(object sender, EventArgs e)
{
    string locale;
    uint number;
    CultureInfo culture;

    // Return if string is empty
    if (String.IsNullOrEmpty(this.inputNumber.Text))
        return;

    // Get locale of web request to determine possible format of number
    if (Request.UserLanguages.Length == 0)
        return;
    locale = Request.UserLanguages[0];
    if (String.IsNullOrEmpty(locale))
        return;

    // Instantiate CultureInfo object for the user's locale
    culture = new CultureInfo(locale);

    // Convert user input from a string to a number
    try
    {
        number = UInt32.Parse(this.inputNumber.Text, culture.NumberFormat);
    }
    catch (FormatException)
    {
        return;
    }
    catch (Exception)
    {
        return;
    }
    // Output number to label on web form
    this.outputNumber.Text = "Number is " + number.ToString();
}
Protected Sub OKToUInteger_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OKToUInteger.Click
   Dim locale As String
   Dim culture As CultureInfo
   Dim number As UInteger

   ' Return if string is empty
   If String.IsNullOrEmpty(Me.inputNumber.Text) Then Exit Sub

   ' Get locale of web request to determine possible format of number
   If Request.UserLanguages.Length = 0 Then Exit Sub
   locale = Request.UserLanguages(0)
   If String.IsNullOrEmpty(locale) Then Exit Sub

   ' Instantiate CultureInfo object for the user's locale
   culture = New CultureInfo(locale)

   ' Convert user input from a string to a number
   Try
      number = UInt32.Parse(Me.inputNumber.Text, culture.NumberFormat)
   Catch ex As FormatException
      Exit Sub
   Catch ex As Exception
      Exit Sub
   End Try

   ' Output number to label on web form
   Me.outputNumber.Text = "Number is " & number.ToString()
End Sub

Comentarios

El s parámetro contiene un número del formulario:

[ws] [sign] digits[ws]

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

Elemento Descripción
ws Espacio en blanco opcional.
sign Un signo opcional o un signo negativo si s representa el valor cero.
dígitos Secuencia de dígitos comprendidos entre 0 y 9.

El parámetro s se interpreta con el NumberStyles.Integer estilo . Además de los dígitos decimales del valor entero sin signo, solo se permiten espacios iniciales y finales junto con un signo inicial. (Si el signo negativo está presente, s debe representar un valor de cero o el método produce un OverflowException. ) Para definir explícitamente los elementos de estilo junto con la información de formato específica de la referencia cultural que puede estar presente en s, use el Parse(String, NumberStyles, IFormatProvider) método .

El provider parámetro es una IFormatProvider implementación cuyo GetFormat método devuelve un NumberFormatInfo objeto que proporciona información específica de la referencia cultural sobre el formato de s. Hay tres maneras de usar el provider parámetro para proporcionar información de formato personalizada a la operación de análisis:

  • Puede pasar el objeto real NumberFormatInfo que proporciona información de formato. (Su implementación de GetFormat simplemente devuelve a sí mismo).

  • Puede pasar un CultureInfo objeto que especifique la referencia cultural cuyo formato se va a usar. Su NumberFormat propiedad proporciona información de formato.

  • Puede pasar una implementación personalizada IFormatProvider . Su GetFormat método debe crear instancias y devolver el NumberFormatInfo objeto que proporciona información de formato.

Si provider es null, se usa para NumberFormatInfo la referencia cultural actual.

Consulte también

Se aplica a

Parse(String, NumberStyles)

Source:
UInt32.cs
Source:
UInt32.cs
Source:
UInt32.cs

Importante

Esta API no es conforme a CLS.

Alternativa conforme a CLS
System.Int64.Parse(String)

Convierte la representación en forma de cadena de un número del estilo especificado en el entero de 32 bits sin signo equivalente.

public:
 static System::UInt32 Parse(System::String ^ s, System::Globalization::NumberStyles style);
[System.CLSCompliant(false)]
public static uint Parse (string s, System.Globalization.NumberStyles style);
public static uint Parse (string s, System.Globalization.NumberStyles style);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles -> uint32
static member Parse : string * System.Globalization.NumberStyles -> uint32
Public Shared Function Parse (s As String, style As NumberStyles) As UInteger

Parámetros

s
String

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 los valores de enumeración que especifican el formato permitido de s. Un valor que se especifica de forma habitual es Integer.

Devoluciones

Entero sin signo de 32 bits equivalente al número especificado en s.

Atributos

Excepciones

style no es un valor NumberStyles.

o bien

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

s no está en un formato compatible con style.

s representa un número menor que UInt32.MinValue o mayor que UInt32.MaxValue.

o bien

s incluye dígitos fraccionarios distintos de cero.

Ejemplos

En el ejemplo siguiente se intenta analizar cada elemento de una matriz de cadenas mediante una serie de NumberStyles valores.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] values= { " 214309 ", "1,064,181", "(0)", "10241+", " + 21499 ", 
                         " +21499 ", "122153.00", "1e03ff", "91300.0e-2" };
      NumberStyles whitespace =  NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite;
      NumberStyles[] styles= { NumberStyles.None, whitespace, 
                               NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace, 
                               NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol, 
                               NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint };

      // Attempt to convert each number using each style combination.
      foreach (string value in values)
      {
         Console.WriteLine("Attempting to convert '{0}':", value);
         foreach (NumberStyles style in styles)
         {
            try {
               uint number = UInt32.Parse(value, style);
               Console.WriteLine("   {0}: {1}", style, number);
            }   
            catch (FormatException) {
               Console.WriteLine("   {0}: Bad Format", style);
            }   
            catch (OverflowException)
            {
               Console.WriteLine("   {0}: Overflow", value);         
            }         
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output:
//    Attempting to convert ' 214309 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: 214309
//       Integer, AllowTrailingSign: 214309
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '1,064,181':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: 1064181
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '(0)':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '10241+':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: 10241
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert ' + 21499 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert ' +21499 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: 21499
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '122153.00':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 122153
//    
//    Attempting to convert '1e03ff':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '91300.0e-2':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 913
open System
open System.Globalization

let values = 
    [| " 214309 "; "1,064,181"; "(0)"; "10241+"; " + 21499 " 
       " +21499 "; "122153.00"; "1e03ff"; "91300.0e-2" |]

let whitespace =  NumberStyles.AllowLeadingWhite ||| NumberStyles.AllowTrailingWhite
let styles = 
    [| NumberStyles.None; whitespace 
       NumberStyles.AllowLeadingSign ||| NumberStyles.AllowTrailingSign ||| whitespace
       NumberStyles.AllowThousands ||| NumberStyles.AllowCurrencySymbol
       NumberStyles.AllowExponent ||| NumberStyles.AllowDecimalPoint |]

// Attempt to convert each number using each style combination.
for value in values do
    printfn $"Attempting to convert '{value}':"
    for style in styles do
        try
            let number = UInt32.Parse(value, style)
            printfn $"   {style}: {number}"
        with
        | :? FormatException ->
            printfn $"   {style}: Bad Format"
        | :? OverflowException ->
            printfn $"   {value}: Overflow"
    printfn "" 
// The example displays the following output:
//    Attempting to convert ' 214309 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: 214309
//       Integer, AllowTrailingSign: 214309
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '1,064,181':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: 1064181
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '(0)':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '10241+':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: 10241
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert ' + 21499 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert ' +21499 ':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: 21499
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '122153.00':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 122153
//    
//    Attempting to convert '1e03ff':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: Bad Format
//    
//    Attempting to convert '91300.0e-2':
//       None: Bad Format
//       AllowLeadingWhite, AllowTrailingWhite: Bad Format
//       Integer, AllowTrailingSign: Bad Format
//       AllowThousands, AllowCurrencySymbol: Bad Format
//       AllowDecimalPoint, AllowExponent: 913
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim values() As String = { " 214309 ", "1,064,181", "(0)", "10241+", _
                                 " + 21499 ", " +21499 ", "122153.00", _
                                 "1e03ff", "91300.0e-2" }
      Dim whitespace As NumberStyles =  NumberStyles.AllowLeadingWhite Or NumberStyles.AllowTrailingWhite
      Dim styles() As NumberStyles = { NumberStyles.None, _
                                       whitespace, _
                                       NumberStyles.AllowLeadingSign Or NumberStyles.AllowTrailingSign Or whitespace, _
                                       NumberStyles.AllowThousands Or NumberStyles.AllowCurrencySymbol, _
                                       NumberStyles.AllowExponent Or NumberStyles.AllowDecimalPoint }

      ' Attempt to convert each number using each style combination.
      For Each value As String In values
         Console.WriteLine("Attempting to convert '{0}':", value)
         For Each style As NumberStyles In styles
            Try
               Dim number As UInteger = UInt32.Parse(value, style)
               Console.WriteLine("   {0}: {1}", style, number)
            Catch e As FormatException
               Console.WriteLine("   {0}: Bad Format", style)
            Catch e As OverflowException
               Console.WriteLine("   {0}: Overflow", value)         
            End Try         
         Next
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output:
'    Attempting to convert ' 214309 ':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: 214309
'       Integer, AllowTrailingSign: 214309
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '1,064,181':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: 1064181
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '(0)':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '10241+':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: 10241
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert ' + 21499 ':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert ' +21499 ':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: 21499
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '122153.00':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: 122153
'    
'    Attempting to convert '1e03ff':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: Bad Format
'    
'    Attempting to convert '91300.0e-2':
'       None: Bad Format
'       AllowLeadingWhite, AllowTrailingWhite: Bad Format
'       Integer, AllowTrailingSign: Bad Format
'       AllowThousands, AllowCurrencySymbol: Bad Format
'       AllowDecimalPoint, AllowExponent: 913

Comentarios

El style parámetro define los elementos de estilo (como el espacio en blanco, el símbolo de signo positivo o negativo, el símbolo separador de grupo o el símbolo de separador decimal) que se permiten en el s parámetro para que la operación de análisis se realice correctamente. style debe ser una combinación de marcas de bits de la NumberStyles enumeración. El style parámetro hace que esta sobrecarga de método sea útil cuando s contiene la representación de cadena de un valor hexadecimal, cuando el sistema numérico (decimal o hexadecimal) representado s por solo se conoce en tiempo de ejecución, o cuando se desea denegar el espacio en blanco o un símbolo de signo en s.

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 de los corchetes ([ y ]) son opcionales. Si style incluye NumberStyles.AllowHexSpecifier, el s parámetro puede contener 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 y puede aparecer al final de s si style incluye la NumberStyles.AllowTrailingWhitestyle marca.
$ Símbolo de moneda específico de la referencia cultural. Su posición en la cadena se define mediante las NumberFormatInfo.CurrencyNegativePattern propiedades y NumberFormatInfo.CurrencyPositivePattern de la referencia cultural actual. El símbolo de moneda de la referencia cultural actual 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, el símbolo de signo negativo solo se puede usar con cero; de lo contrario, el método produce una OverflowExceptionexcepción .
dígitos

fractional_digits

exponential_digits
Secuencia de dígitos de 0 a 9. Para fractional_digits, solo el dígito 0 es válido.
, Símbolo separador de grupo específico de la referencia cultural. El separador de grupos de la referencia cultural actual 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 actual puede aparecer en s si style incluye la NumberStyles.AllowDecimalPoint marca . Solo el dígito 0 puede aparecer como un dígito fraccionario para que la operación de análisis se realice correctamente; si fractional_digits incluye cualquier otro dígito, se produce una FormatException excepción .
E 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 .
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 solo (que corresponde al NumberStyles.None estilo) siempre analiza correctamente si se encuentra en el intervalo del UInt32 tipo. La mayoría de los miembros restantes NumberStyles controlan los elementos que pueden estar presentes, pero no son necesarios para estar presentes, en la 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.

Valor de NumberStyles Elementos permitidos además s de dígitos
None Solo el elemento digits .
AllowDecimalPoint Los elementos decimal point (.) y fractional-digits .
AllowExponent Carácter "e" o "E", que indica la notación exponencial, junto con exponential_digits.
AllowLeadingWhite Elemento ws al principio de s.
AllowTrailingWhite Elemento ws al final de s.
AllowLeadingSign Elemento de signo al principio de s.
AllowTrailingSign Elemento de signo al final de s.
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, 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 decimal (.). El s parámetro también puede usar la notación exponencial.
Number Elementos wsseparadores de signgrupo (,) y separadores decimales (.).
Any Todos los elementos. Sin embargo, s no puede representar un número hexadecimal.

A diferencia de los demás NumberStyles valores, que permiten, pero no requieren, la presencia de elementos de estilo concretos en s, el NumberStyles.AllowHexSpecifier valor de estilo significa que los caracteres numéricos individuales de s siempre se interpretan como caracteres hexadecimales. Los caracteres hexadecimales válidos son 0-9, A-F y a-f. No se permite un prefijo, como "0x". Las únicas marcas que se pueden combinar con el style parámetro son NumberStyles.AllowLeadingWhite y NumberStyles.AllowTrailingWhite. (La NumberStyles enumeración incluye un estilo de número compuesto, NumberStyles.HexNumber, que incluye ambas marcas de espacio en blanco).

Las únicas marcas que se pueden combinar con el style parámetro son NumberStyles.AllowLeadingWhite y NumberStyles.AllowTrailingWhite. (La NumberStyles enumeración incluye un estilo de número compuesto, NumberStyles.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 s parámetro se analiza mediante la información de formato de un NumberFormatInfo objeto que se inicializa para la referencia cultural del sistema actual. Para especificar la referencia cultural cuya información de formato se usa para la operación de análisis, llame a la Parse(String, NumberStyles, IFormatProvider) sobrecarga.

Consulte también

Se aplica a

Parse(ReadOnlySpan<Char>, IFormatProvider)

Source:
UInt32.cs
Source:
UInt32.cs
Source:
UInt32.cs

Analiza un intervalo de caracteres en un valor.

public:
 static System::UInt32 Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<System::UInt32>::Parse;
public static uint Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> uint32
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As UInteger

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.

Devoluciones

Resultado del análisis sde .

Implementaciones

Se aplica a

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Source:
UInt32.cs
Source:
UInt32.cs

Analiza un intervalo de caracteres UTF-8 en un valor.

public:
 static System::UInt32 Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<System::UInt32>::Parse;
public static uint Parse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> uint32
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As UInteger

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.

Devoluciones

Resultado del análisis utf8Textde .

Implementaciones

Se aplica a

Parse(String)

Source:
UInt32.cs
Source:
UInt32.cs
Source:
UInt32.cs

Importante

Esta API no es conforme a CLS.

Alternativa conforme a CLS
System.Int64.Parse(String)

Convierte la representación en forma de cadena de un número en el entero de 32 bits sin signo equivalente.

public:
 static System::UInt32 Parse(System::String ^ s);
[System.CLSCompliant(false)]
public static uint Parse (string s);
public static uint Parse (string s);
[<System.CLSCompliant(false)>]
static member Parse : string -> uint32
static member Parse : string -> uint32
Public Shared Function Parse (s As String) As UInteger

Parámetros

s
String

Cadena que representa el número que se va a convertir.

Devoluciones

Entero sin signo de 32 bits equivalente al número incluido en s.

Atributos

Excepciones

El parámetro s es null.

El parámetro s no tiene el formato correcto.

El s parámetro representa un número menor que UInt32.MinValue o mayor que UInt32.MaxValue.

Ejemplos

En el ejemplo siguiente se usa el Parse(String) método para analizar una matriz de valores de cadena.

string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127",
                    "0xFA1B", "163042", "-10", "2147483648", 
                    "14065839182", "16e07", "134985.0", "-12034" };
foreach (string value in values)
{
   try {
      uint number = UInt32.Parse(value); 
      Console.WriteLine("{0} --> {1}", value, number);
   }
   catch (FormatException) {
      Console.WriteLine("{0}: Bad Format", value);
   }   
   catch (OverflowException) {
      Console.WriteLine("{0}: Overflow", value);   
   }  
}
// The example displays the following output:
//       +13230 --> 13230
//       -0 --> 0
//       1,390,146: Bad Format
//       $190,235,421,127: Bad Format
//       0xFA1B: Bad Format
//       163042 --> 163042
//       -10: Overflow
//       2147483648 --> 2147483648
//       14065839182: Overflow
//       16e07: Bad Format
//       134985.0: Bad Format
//       -12034: Overflow
open System

let values = 
    [| "+13230"; "-0"; "1,390,146"; "$190,235,421,127"
       "0xFA1B"; "163042"; "-10"; "2147483648"
       "14065839182"; "16e07"; "134985.0"; "-12034" |]

for value in values do
    try
        let number = UInt32.Parse value 
        printfn $"{value} --> {number}"
    with
    | :? FormatException ->
        printfn $"{value}: Bad Format"
    | :? OverflowException ->
        printfn $"{value}: Overflow"
// The example displays the following output:
//       +13230 --> 13230
//       -0 --> 0
//       1,390,146: Bad Format
//       $190,235,421,127: Bad Format
//       0xFA1B: Bad Format
//       163042 --> 163042
//       -10: Overflow
//       2147483648 --> 2147483648
//       14065839182: Overflow
//       16e07: Bad Format
//       134985.0: Bad Format
//       -12034: Overflow
Dim values() As String = { "+13230", "-0", "1,390,146", "$190,235,421,127", 
                           "0xFA1B", "163042", "-10", "2147483648",  
                           "14065839182", "16e07", "134985.0", "-12034" }
For Each value As String In values
   Try
      Dim number As UInteger = UInt32.Parse(value) 
      Console.WriteLine("{0} --> {1}", value, number)
   Catch e As FormatException
      Console.WriteLine("{0}: Bad Format", value)
   Catch e As OverflowException
      Console.WriteLine("{0}: Overflow", value)   
   End Try  
Next
' The example displays the following output:
'       +13230 --> 13230
'       -0 --> 0
'       1,390,146: Bad Format
'       $190,235,421,127: Bad Format
'       0xFA1B: Bad Format
'       163042 --> 163042
'       -10: Overflow
'       2147483648 --> 2147483648
'       14065839182: Overflow
'       16e07: Bad Format
'       134985.0: Bad Format
'       -12034: Overflow

Comentarios

El s parámetro debe ser la representación de cadena de un número en 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. Sin embargo, el símbolo de signo negativo solo se puede usar con cero; de lo contrario, el método produce una OverflowExceptionexcepción .
dígitos Secuencia de dígitos comprendidos entre 0 y 9. Se omiten los ceros iniciales.

Nota

La cadena especificada por el s parámetro se interpreta mediante el NumberStyles.Integer estilo . No puede contener separadores de grupo ni separadores decimales y no puede tener una parte decimal.

El s parámetro se analiza mediante la información de formato de un System.Globalization.NumberFormatInfo objeto que se inicializa para la referencia cultural del sistema actual. Para obtener más información, vea NumberFormatInfo.CurrentInfo. Para analizar una cadena mediante la información de formato de una referencia cultural específica, use el Parse(String, IFormatProvider) método .

Consulte también

Se aplica a