UInt16.Parse Método
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Convierte la representación en forma de cadena de un número en el entero de 16 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 16 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 16 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 16 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 16 bits sin signo equivalente. Este método no es conforme a CLS. La alternativa conforme a CLS es Parse(String, NumberStyles). |
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 16 bits sin signo equivalente. |
Parse(String, NumberStyles, IFormatProvider)
- Source:
- UInt16.cs
- Source:
- UInt16.cs
- Source:
- UInt16.cs
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 16 bits sin signo equivalente.
public:
static System::UInt16 Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
static System::UInt16 Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<System::UInt16>::Parse;
[System.CLSCompliant(false)]
public static ushort Parse (string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static ushort Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static ushort Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> uint16
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> uint16
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As UShort
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 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 16 bits equivalente al número especificado en s
.
Implementaciones
- Atributos
Excepciones
s
es null
.
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 UInt16.MinValue o mayor que UInt16.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 de 16 bits sin signo.
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 = { "1702", "+1702.0", "+1702,0", "-1032.00",
"-1032,00", "1045.1", "1045,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,
UInt16.Parse(value, style, ci));
}
catch (FormatException) {
Console.WriteLine(" Unable to parse '{0}'.", value);
}
catch (OverflowException) {
Console.WriteLine(" '{0}' is out of range of the UInt16 type.",
value);
}
}
}
}
}
}
// The example displays the following output:
// Parsing strings using the English (United States) culture
// Style: Integer
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Unable to parse '+1702,0'.
// Unable to parse '-1032.00'.
// Unable to parse '-1032,00'.
// Unable to parse '1045.1'.
// Unable to parse '1045,1'.
// Style: Integer, AllowDecimalPoint
// Converted '1702' to 1702.
// Converted '+1702.0' to 1702.
// Unable to parse '+1702,0'.
// '-1032.00' is out of range of the UInt16 type.
// Unable to parse '-1032,00'.
// '1045.1' is out of range of the UInt16 type.
// Unable to parse '1045,1'.
// Parsing strings using the French (France) culture
// Style: Integer
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Unable to parse '+1702,0'.
// Unable to parse '-1032.00'.
// Unable to parse '-1032,00'.
// Unable to parse '1045.1'.
// Unable to parse '1045,1'.
// Style: Integer, AllowDecimalPoint
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Converted '+1702,0' to 1702.
// Unable to parse '-1032.00'.
// '-1032,00' is out of range of the UInt16 type.
// Unable to parse '1045.1'.
// '1045,1' is out of range of the UInt16 type.
open System
open System.Globalization
let cultureNames = [| "en-US"; "fr-FR" |]
let styles =
[| NumberStyles.Integer; NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint |]
let values =
[| "1702"; "+1702.0"; "+1702,0"; "-1032.00"; "-1032,00"; "1045.1"; "1045,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 {UInt16.Parse(value, style, ci)}."
with
| :? FormatException ->
printfn $" Unable to parse '{value}'."
| :? OverflowException ->
printfn $" '{value}' is out of range of the UInt16 type."
// The example displays the following output:
// Parsing strings using the English (United States) culture
// Style: Integer
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Unable to parse '+1702,0'.
// Unable to parse '-1032.00'.
// Unable to parse '-1032,00'.
// Unable to parse '1045.1'.
// Unable to parse '1045,1'.
// Style: Integer, AllowDecimalPoint
// Converted '1702' to 1702.
// Converted '+1702.0' to 1702.
// Unable to parse '+1702,0'.
// '-1032.00' is out of range of the UInt16 type.
// Unable to parse '-1032,00'.
// '1045.1' is out of range of the UInt16 type.
// Unable to parse '1045,1'.
// Parsing strings using the French (France) culture
// Style: Integer
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Unable to parse '+1702,0'.
// Unable to parse '-1032.00'.
// Unable to parse '-1032,00'.
// Unable to parse '1045.1'.
// Unable to parse '1045,1'.
// Style: Integer, AllowDecimalPoint
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Converted '+1702,0' to 1702.
// Unable to parse '-1032.00'.
// '-1032,00' is out of range of the UInt16 type.
// Unable to parse '1045.1'.
// '1045,1' is out of range of the UInt16 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 = { "1702", "+1702.0", "+1702,0", "-1032.00", _
"-1032,00", "1045.1", "1045,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, _
UInt16.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 UInt16 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 '1702' to 1702.
' Unable to parse '+1702.0'.
' Unable to parse '+1702,0'.
' Unable to parse '-1032.00'.
' Unable to parse '-1032,00'.
' Unable to parse '1045.1'.
' Unable to parse '1045,1'.
' Style: Integer, AllowDecimalPoint
' Converted '1702' to 1702.
' Converted '+1702.0' to 1702.
' Unable to parse '+1702,0'.
' '-1032.00' is out of range of the UInt16 type.
' Unable to parse '-1032,00'.
' '1045.1' is out of range of the UInt16 type.
' Unable to parse '1045,1'.
' Parsing strings using the French (France) culture
' Style: Integer
' Converted '1702' to 1702.
' Unable to parse '+1702.0'.
' Unable to parse '+1702,0'.
' Unable to parse '-1032.00'.
' Unable to parse '-1032,00'.
' Unable to parse '1045.1'.
' Unable to parse '1045,1'.
' Style: Integer, AllowDecimalPoint
' Converted '1702' to 1702.
' Unable to parse '+1702.0'.
' Converted '+1702,0' to 1702.
' Unable to parse '-1032.00'.
' '-1032,00' is out of range of the UInt16 type.
' Unable to parse '1045.1'.
' '1045,1' is out of range of the UInt16 type.
Comentarios
El style
parámetro define los elementos de estilo (como el espacio 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 de separador 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 | 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 al NumberStyles.None estilo) 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 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 | El 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 | Signo después de 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 dígitos hexadecimales válidos son de 0 a 9, de a f y de A a F. No se admite un prefijo, como "0x", y hace que se produzca un error en la operación de análisis. Las únicas marcas que se pueden combinar con NumberStyles.AllowHexSpecifier 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:
- UInt16.cs
- Source:
- UInt16.cs
- Source:
- UInt16.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 16 bits equivalente.
public static ushort Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
[System.CLSCompliant(false)]
public static ushort Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider provider = default);
[System.CLSCompliant(false)]
public static ushort Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> uint16
[<System.CLSCompliant(false)>]
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> uint16
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As UShort
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 16 bits equivalente al número especificado en s
.
Implementaciones
- Atributos
Se aplica a
Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)
- Source:
- UInt16.cs
- Source:
- UInt16.cs
Analiza un intervalo de caracteres UTF-8 en un valor.
public static ushort Parse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> uint16
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As UShort
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 utf8Text
de .
Implementaciones
Se aplica a
Parse(String, IFormatProvider)
- Source:
- UInt16.cs
- Source:
- UInt16.cs
- Source:
- UInt16.cs
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 16 bits sin signo equivalente.
public:
static System::UInt16 Parse(System::String ^ s, IFormatProvider ^ provider);
public:
static System::UInt16 Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<System::UInt16>::Parse;
[System.CLSCompliant(false)]
public static ushort Parse (string s, IFormatProvider provider);
public static ushort Parse (string s, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static ushort Parse (string s, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * IFormatProvider -> uint16
static member Parse : string * IFormatProvider -> uint16
Public Shared Function Parse (s As String, provider As IFormatProvider) As UShort
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 16 bits equivalente al número especificado en s
.
Implementaciones
- Atributos
Excepciones
s
es null
.
s
no tiene el formato correcto.
s
representa un número menor que UInt16.MinValue o mayor que UInt16.MaxValue.
Ejemplos
En el ejemplo siguiente se crea una instancia de una referencia cultural personalizada que usa dos signos más (++) como signo positivo. A continuación, llama al Parse(String, IFormatProvider) método para analizar una matriz de cadenas mediante CultureInfo objetos que representan esta referencia cultural personalizada y la referencia cultural invariable.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
// Define a custom culture that uses "++" as a positive sign.
CultureInfo ci = new CultureInfo("");
ci.NumberFormat.PositiveSign = "++";
// Create an array of cultures.
CultureInfo[] cultures = { ci, CultureInfo.InvariantCulture };
// Create an array of strings to parse.
string[] values = { "++1403", "-0", "+0", "+16034",
Int16.MinValue.ToString(), "14.0", "18012" };
// Parse the strings using each culture.
foreach (CultureInfo culture in cultures)
{
Console.WriteLine("Parsing with the '{0}' culture.", culture.Name);
foreach (string value in values)
{
try {
ushort number = UInt16.Parse(value, culture);
Console.WriteLine(" Converted '{0}' to {1}.", value, number);
}
catch (FormatException) {
Console.WriteLine(" The format of '{0}' is invalid.", value);
}
catch (OverflowException) {
Console.WriteLine(" '{0}' is outside the range of a UInt16 value.", value);
}
}
}
}
}
// The example displays the following output:
// Parsing with the culture.
// Converted '++1403' to 1403.
// Converted '-0' to 0.
// The format of '+0' is invalid.
// The format of '+16034' is invalid.
// '-32768' is outside the range of a UInt16 value.
// The format of '14.0' is invalid.
// Converted '18012' to 18012.
// Parsing with the '' culture.
// The format of '++1403' is invalid.
// Converted '-0' to 0.
// Converted '+0' to 0.
// Converted '+16034' to 16034.
// '-32768' is outside the range of a UInt16 value.
// The format of '14.0' is invalid.
// Converted '18012' to 18012.
open System
open System.Globalization
// Define a custom culture that uses "++" as a positive sign.
let ci = CultureInfo ""
ci.NumberFormat.PositiveSign <- "++"
// Create an array of cultures.
let cultures = [| ci; CultureInfo.InvariantCulture |]
// Create an array of strings to parse.
let values =
[| "++1403"; "-0"; "+0"; "+16034"
string Int16.MinValue; "14.0"; "18012" |]
// Parse the strings using each culture.
for culture in cultures do
printfn $"Parsing with the '{culture.Name}' culture."
for value in values do
try
let number = UInt16.Parse(value, culture)
printfn $" Converted '{value}' to {number}."
with
| :? FormatException ->
printfn $" The format of '{value}' is invalid."
| :? OverflowException ->
printfn $" '{value}' is outside the range of a UInt16 value."
// The example displays the following output:
// Parsing with the culture.
// Converted '++1403' to 1403.
// Converted '-0' to 0.
// The format of '+0' is invalid.
// The format of '+16034' is invalid.
// '-32768' is outside the range of a UInt16 value.
// The format of '14.0' is invalid.
// Converted '18012' to 18012.
// Parsing with the '' culture.
// The format of '++1403' is invalid.
// Converted '-0' to 0.
// Converted '+0' to 0.
// Converted '+16034' to 16034.
// '-32768' is outside the range of a UInt16 value.
// The format of '14.0' is invalid.
// Converted '18012' to 18012.
Imports System.Globalization
Module Example
Public Sub Main()
' Define a custom culture that uses "++" as a positive sign.
Dim ci As CultureInfo = New CultureInfo("")
ci.NumberFormat.PositiveSign = "++"
' Create an array of cultures.
Dim cultures() As CultureInfo = { ci, CultureInfo.InvariantCulture }
' Create an array of strings to parse.
Dim values() As String = { "++1403", "-0", "+0", "+16034", _
Int16.MinValue.ToString(), "14.0", "18012" }
' Parse the strings using each culture.
For Each culture As CultureInfo In cultures
Console.WriteLine("Parsing with the '{0}' culture.", culture.Name)
For Each value As String In values
Try
Dim number As UShort = UInt16.Parse(value, culture)
Console.WriteLine(" Converted '{0}' to {1}.", value, number)
Catch e As FormatException
Console.WriteLine(" The format of '{0}' is invalid.", value)
Catch e As OverflowException
Console.WriteLine(" '{0}' is outside the range of a UInt16 value.", value)
End Try
Next
Next
End Sub
End Module
' The example displays the following output:
' Parsing with the culture.
' Converted '++1403' to 1403.
' Converted '-0' to 0.
' The format of '+0' is invalid.
' The format of '+16034' is invalid.
' '-32768' is outside the range of a UInt16 value.
' The format of '14.0' is invalid.
' Converted '18012' to 18012.
' Parsing with the '' culture.
' The format of '++1403' is invalid.
' Converted '-0' to 0.
' Converted '+0' to 0.
' Converted '+16034' to 16034.
' '-32768' is outside the range of a UInt16 value.
' The format of '14.0' is invalid.
' Converted '18012' to 18012.
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 de byte, 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:
- UInt16.cs
- Source:
- UInt16.cs
- Source:
- UInt16.cs
Importante
Esta API no es conforme a CLS.
Convierte la representación en forma de cadena de un número del estilo especificado en el entero de 16 bits sin signo equivalente.
Este método no es conforme a CLS. La alternativa conforme a CLS es Parse(String, NumberStyles).
public:
static System::UInt16 Parse(System::String ^ s, System::Globalization::NumberStyles style);
[System.CLSCompliant(false)]
public static ushort Parse (string s, System.Globalization.NumberStyles style);
public static ushort Parse (string s, System.Globalization.NumberStyles style);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles -> uint16
static member Parse : string * System.Globalization.NumberStyles -> uint16
Public Shared Function Parse (s As String, style As NumberStyles) As UShort
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 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 16 bits equivalente al número especificado en s
.
- Atributos
Excepciones
s
es null
.
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 UInt16.MinValue o mayor que UInt16.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 = { " 214 ", "1,064", "(0)", "1241+", " + 214 ", " +214 ", "2153.0", "1e03", "1300.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 {
ushort number = UInt16.Parse(value, style);
Console.WriteLine(" {0}: {1}", style, number);
}
catch (FormatException) {
Console.WriteLine(" {0}: Bad Format", style);
}
}
Console.WriteLine();
}
}
}
// The example display the following output:
// Attempting to convert ' 214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: 214
// Integer, AllowTrailingSign: 214
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '1,064':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: 1064
// 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 '1241+':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: 1241
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert ' + 214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert ' +214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: 214
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '2153.0':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 2153
//
// Attempting to convert '1e03':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 1000
//
// Attempting to convert '1300.0e-2':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 13
open System
open System.Globalization
let values = [| " 214 "; "1,064"; "(0)"; "1241+"; " + 214 "; " +214 "; "2153.0"; "1e03"; "1300.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 = UInt16.Parse(value, style)
printfn $" {style}: {number}"
with :? FormatException ->
printfn $" {style}: Bad Format"
printfn ""
// The example display the following output:
// Attempting to convert ' 214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: 214
// Integer, AllowTrailingSign: 214
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '1,064':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: 1064
// 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 '1241+':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: 1241
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert ' + 214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert ' +214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: 214
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '2153.0':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 2153
//
// Attempting to convert '1e03':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 1000
//
// Attempting to convert '1300.0e-2':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 13
Imports System.Globalization
Module Example
Public Sub Main()
Dim values() As String = { " 214 ", "1,064", "(0)", "1241+", " + 214 ", " +214 ", "2153.0", "1e03", "1300.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 UShort = UInt16.Parse(value, style)
Console.WriteLine(" {0}: {1}", style, number)
Catch e As FormatException
Console.WriteLine(" {0}: Bad Format", style)
End Try
Next
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' Attempting to convert ' 214 ':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: 214
' Integer, AllowTrailingSign: 214
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert '1,064':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: 1064
' 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 '1241+':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: 1241
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert ' + 214 ':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert ' +214 ':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: 214
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert '2153.0':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: 2153
'
' Attempting to convert '1e03':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: 1000
'
' Attempting to convert '1300.0e-2':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: 13
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 | 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 . |
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 solo con dígitos (que corresponde al NumberStyles.None estilo) siempre analiza correctamente si está en el intervalo del UInt16 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 | Elementos decimales (.) y fracciones de dígitos . |
AllowExponent | El 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 sign al principio de s . |
AllowTrailingSign | Elemento sign 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 s y el símbolo de separador decimal (.). El s parámetro también puede usar la notación exponencial. |
Number | Elementos ws separadores sign de grupo (,) y separador decimal (.). |
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 valor de NumberStyles.AllowHexSpecifier 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 admite un prefijo, como "0x", y hace que se produzca un error en la operación de análisis. 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:
- UInt16.cs
- Source:
- UInt16.cs
- Source:
- UInt16.cs
Analiza un intervalo de caracteres en un valor.
public:
static System::UInt16 Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<System::UInt16>::Parse;
public static ushort Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> uint16
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As UShort
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 s
de .
Implementaciones
Se aplica a
Parse(ReadOnlySpan<Byte>, IFormatProvider)
- Source:
- UInt16.cs
- Source:
- UInt16.cs
Analiza un intervalo de caracteres UTF-8 en un valor.
public:
static System::UInt16 Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<System::UInt16>::Parse;
public static ushort Parse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> uint16
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As UShort
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 utf8Text
de .
Implementaciones
Se aplica a
Parse(String)
- Source:
- UInt16.cs
- Source:
- UInt16.cs
- Source:
- UInt16.cs
Convierte la representación en forma de cadena de un número en el entero de 16 bits sin signo equivalente.
public:
static System::UInt16 Parse(System::String ^ s);
[System.CLSCompliant(false)]
public static ushort Parse (string s);
public static ushort Parse (string s);
[<System.CLSCompliant(false)>]
static member Parse : string -> uint16
static member Parse : string -> uint16
Public Shared Function Parse (s As String) As UShort
Parámetros
- s
- String
Una cadena que representa el número que se va a convertir.
Devoluciones
Entero sin signo de 16 bits equivalente al número incluido en s
.
- Atributos
Excepciones
s
es null
.
s
no tiene el formato correcto.
s
representa un número menor que UInt16.MinValue o mayor que UInt16.MaxValue.
Ejemplos
En el ejemplo siguiente se llama al Parse(String) método para convertir cada elemento de una matriz de cadenas en un entero de 16 bits sin signo.
using System;
public class Example
{
public static void Main()
{
string[] values = { "-0", "17", "-12", "185", "66012", "+0",
"", null, "16.1", "28.0", "1,034" };
foreach (string value in values)
{
try {
ushort number = UInt16.Parse(value);
Console.WriteLine("'{0}' --> {1}", value, number);
}
catch (FormatException) {
Console.WriteLine("'{0}' --> Bad Format", value);
}
catch (OverflowException) {
Console.WriteLine("'{0}' --> OverflowException", value);
}
catch (ArgumentNullException) {
Console.WriteLine("'{0}' --> Null", value);
}
}
}
}
// The example displays the following output:
// '-0' --> 0
// '17' --> 17
// '-12' --> OverflowException
// '185' --> 185
// '66012' --> OverflowException
// '+0' --> 0
// '' --> Bad Format
// '' --> Null
// '16.1' --> Bad Format
// '28.0' --> Bad Format
// '1,034' --> Bad Format
open System
let values =
[| "-0"; "17"; "-12"; "185"; "66012"; "+0"
""; null; "16.1"; "28.0"; "1,034" |]
for value in values do
try
let number = UInt16.Parse value
printfn $"'{value}' --> {number}"
with
| :? FormatException ->
printfn $"'{value}' --> Bad Format"
| :? OverflowException ->
printfn $"'{value}' --> OverflowException"
| :? ArgumentNullException ->
printfn $"'{value}' --> Null"
// The example displays the following output:
// '-0' --> 0
// '17' --> 17
// '-12' --> OverflowException
// '185' --> 185
// '66012' --> OverflowException
// '+0' --> 0
// '' --> Bad Format
// '' --> Null
// '16.1' --> Bad Format
// '28.0' --> Bad Format
// '1,034' --> Bad Format
Module Example
Public Sub Main()
Dim values() As String = { "-0", "17", "-12", "185", "66012", _
"+0", "", Nothing, "16.1", "28.0", _
"1,034" }
For Each value As String In values
Try
Dim number As UShort = UInt16.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}' --> OverflowException", value)
Catch e As ArgumentNullException
Console.WriteLine("'{0}' --> Null", value)
End Try
Next
End Sub
End Module
' The example displays the following output:
' '-0' --> 0
' '17' --> 17
' '-12' --> OverflowException
' '185' --> 185
' '66012' --> OverflowException
' '+0' --> 0
' '' --> Bad Format
' '' --> Null
' '16.1' --> Bad Format
' '28.0' --> Bad Format
' '1,034' --> Bad Format
Comentarios
El s
parámetro debe ser la representación de cadena de un número 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. 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
Comentarios
https://aka.ms/ContentUserFeedback.
Próximamente: A lo largo de 2024 iremos eliminando gradualmente las Cuestiones de GitHub como mecanismo de retroalimentación para el contenido y lo sustituiremos por un nuevo sistema de retroalimentación. Para más información, consulta:Enviar y ver comentarios de