Int16.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 con 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ífico de la referencia cultural que se hayan especificado en el entero de 16 bits con 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 de 16 bits con signo 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 en el formato específico de la referencia cultural que se haya especificado en el entero de 16 bits con signo equivalente. |
Parse(String) |
Convierte la representación en forma de cadena de un número en el entero de 16 bits con 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, NumberStyles) |
Convierte la representación en forma de cadena de un número con el estilo especificado en el entero de 16 bits con signo equivalente. |
Parse(String, NumberStyles, IFormatProvider)
- Source:
- Int16.cs
- Source:
- Int16.cs
- Source:
- Int16.cs
Convierte la representación en forma de cadena de un número con el estilo y el formato específico de la referencia cultural que se hayan especificado en el entero de 16 bits con signo equivalente.
public:
static short Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
static short Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<short>::Parse;
public static short Parse (string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static short Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> int16
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As Short
Parámetros
- s
- String
Cadena que contiene un número que se va a convertir.
- 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
Un IFormatProvider que proporciona información de formato específica de la referencia cultural acerca de s
.
Devoluciones
Entero con signo de 16 bits equivalente al número especificado en s
.
Implementaciones
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 Int16.MinValue o mayor que Int16.MaxValue.
o bien
s
incluye dígitos fraccionarios distintos de cero.
Ejemplos
En el ejemplo siguiente se usa una variedad de style
parámetros y provider
para analizar las representaciones de cadena de Int16 los valores.
String^ value;
Int16 number;
NumberStyles style;
// Parse string using "." as the thousands separator
// and " " as the decimal separator.
value = "19 694,00";
style = NumberStyles::AllowDecimalPoint | NumberStyles::AllowThousands;
CultureInfo^ provider = gcnew CultureInfo("fr-FR");
number = Int16::Parse(value, style, provider);
Console::WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
// '19 694,00' converted to 19694.
try
{
number = Int16::Parse(value, style, CultureInfo::InvariantCulture);
Console::WriteLine("'{0}' converted to {1}.", value, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to parse '{0}'.", value);
}
// Displays:
// Unable to parse '19 694,00'.
// Parse string using "$" as the currency symbol for en_GB and
// en-US cultures.
value = "$6,032.00";
style = NumberStyles::Number | NumberStyles::AllowCurrencySymbol;
provider = gcnew CultureInfo("en-GB");
try
{
number = Int16::Parse(value, style, CultureInfo::InvariantCulture);
Console::WriteLine("'{0}' converted to {1}.", value, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to parse '{0}'.", value);
}
// Displays:
// Unable to parse '$6,032.00'.
provider = gcnew CultureInfo("en-US");
number = Int16::Parse(value, style, provider);
Console::WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
// '$6,032.00' converted to 6032.
string value;
short number;
NumberStyles style;
CultureInfo provider;
// Parse string using "." as the thousands separator
// and " " as the decimal separator.
value = "19 694,00";
style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;
provider = new CultureInfo("fr-FR");
number = Int16.Parse(value, style, provider);
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
// '19 694,00' converted to 19694.
try
{
number = Int16.Parse(value, style, CultureInfo.InvariantCulture);
Console.WriteLine("'{0}' converted to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse '{0}'.", value);
}
// Displays:
// Unable to parse '19 694,00'.
// Parse string using "$" as the currency symbol for en_GB and
// en-US cultures.
value = "$6,032.00";
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
provider = new CultureInfo("en-GB");
try
{
number = Int16.Parse(value, style, CultureInfo.InvariantCulture);
Console.WriteLine("'{0}' converted to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse '{0}'.", value);
}
// Displays:
// Unable to parse '$6,032.00'.
provider = new CultureInfo("en-US");
number = Int16.Parse(value, style, provider);
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
// '$6,032.00' converted to 6032.
// Parse string using "." as the thousands separator
// and " " as the decimal separator.
let value = "19 694,00"
let style = NumberStyles.AllowDecimalPoint ||| NumberStyles.AllowThousands
let provider = CultureInfo "fr-FR"
let number = Int16.Parse(value, style, provider)
printfn $"'{value}' converted to {number}."
// Displays:
// '19 694,00' converted to 19694.
try
let number = Int16.Parse(value, style, CultureInfo.InvariantCulture)
printfn $"'{value}' converted to {number}."
with :? FormatException ->
printfn $"Unable to parse '{value}'."
// Displays:
// Unable to parse '19 694,00'.
// Parse string using "$" as the currency symbol for en_GB and
// en-US cultures.
let value = "$6,032.00"
let style = NumberStyles.Number ||| NumberStyles.AllowCurrencySymbol
try
let number = Int16.Parse(value, style, CultureInfo.InvariantCulture)
printfn $"'{value}' converted to {number}."
with :? FormatException ->
printfn $"Unable to parse '{value}'."
// Displays:
// Unable to parse '$6,032.00'.
let provider = CultureInfo "en-US"
let number = Int16.Parse(value, style, provider)
printfn $"'{value}' converted to {number}."
// Displays:
// '$6,032.00' converted to 6032.
Dim value As String
Dim number As Short
Dim style As NumberStyles
Dim provider As CultureInfo
' Parse string using "." as the thousands separator
' and " " as the decimal separator.
value = "19 694,00"
style = NumberStyles.AllowDecimalPoint Or NumberStyles.AllowThousands
provider = New CultureInfo("fr-FR")
number = Int16.Parse(value, style, provider)
Console.WriteLine("'{0}' converted to {1}.", value, number)
' Displays:
' '19 694,00' converted to 19694.
Try
number = Int16.Parse(value, style, CultureInfo.InvariantCulture)
Console.WriteLine("'{0}' converted to {1}.", value, number)
Catch e As FormatException
Console.WriteLine("Unable to parse '{0}'.", value)
End Try
' Displays:
' Unable to parse '19 694,00'.
' Parse string using "$" as the currency symbol for en_GB and
' en-US cultures.
value = "$6,032.00"
style = NumberStyles.Number Or NumberStyles.AllowCurrencySymbol
provider = New CultureInfo("en-GB")
Try
number = Int16.Parse(value, style, CultureInfo.InvariantCulture)
Console.WriteLine("'{0}' converted to {1}.", value, number)
Catch e As FormatException
Console.WriteLine("Unable to parse '{0}'.", value)
End Try
' Displays:
' Unable to parse '$6,032.00'.
provider = New CultureInfo("en-US")
number = Int16.Parse(value, style, provider)
Console.WriteLine("'{0}' converted to {1}.", value, number)
' Displays:
' '$6,032.00' converted to 6032.
Comentarios
El style
parámetro define los elementos de estilo (como el espacio en blanco o el signo positivo) que se permiten en el s
parámetro para que la operación de análisis se realice correctamente. Debe ser una combinación de marcas de bits de la NumberStyles enumeración. Según el valor de style
, el s
parámetro puede incluir los siguientes elementos:
[ws] [$] [sign] [digits,]digits[.fractional_digits][e[sign]digits][ws]
O bien, si style
incluye AllowHexSpecifier:
[ws]hexdigits[ws]
Los elementos de los corchetes ([ y ]) son opcionales. En esta tabla se describe cada elemento.
Elemento | Descripción |
---|---|
ws | Espacio en blanco opcional. El espacio en blanco puede aparecer al principio de s si incluye la NumberStyles.AllowLeadingWhite marca o al final de s si style incluye la NumberStyles.AllowTrailingWhite marca.style |
$ | Símbolo de moneda específico de la referencia cultural. Su posición en la cadena se define mediante la NumberFormatInfo.CurrencyPositivePattern propiedad y NumberFormatInfo.CurrencyNegativePattern 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 . |
dígitos | Secuencia de dígitos de 0 a 9. |
, | Símbolo separador de miles específico de la referencia cultural. El símbolo separador de miles 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 . |
fractional_digits | Secuencia del dígito 0. Los dígitos fraccionarios pueden aparecer en s si style incluye la NumberStyles.AllowDecimalPoint marca . Si aparece algún dígito distinto de 0 en fractional_digits, el método produce un OverflowException. |
e | El carácter "e" o "E", que indica que s se puede representar en notación exponencial. El s parámetro puede representar un número en notación exponencial si style incluye la NumberStyles.AllowExponent marca . Sin embargo, el s parámetro debe representar un número en el intervalo del tipo de Int16 datos y no puede tener un componente fraccionaria distinto de cero. |
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. La mayoría de los elementos de control de miembros restantes NumberStyles que pueden ser pero que 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 de NumberStyles no compuestos | Elementos permitidos en s además de dígitos |
---|---|
NumberStyles.None | Solo dígitos decimales. |
NumberStyles.AllowDecimalPoint | Los elementos . y fractional_digits . Sin embargo, fractional_digits debe constar de solo uno o más 0 dígitos o se produce una OverflowException excepción . |
NumberStyles.AllowExponent | El s parámetro también puede usar la notación exponencial. |
NumberStyles.AllowLeadingWhite | Elemento ws al principio de s . |
NumberStyles.AllowTrailingWhite | Elemento ws al final de s . |
NumberStyles.AllowLeadingSign | Un signo puede aparecer antes de los dígitos. |
NumberStyles.AllowTrailingSign | Un signo puede aparecer después de los dígitos. |
NumberStyles.AllowParentheses | Elemento de signo en forma de paréntesis que incluye el valor numérico. |
NumberStyles.AllowThousands | Elemento , . |
NumberStyles.AllowCurrencySymbol | Elemento $. |
Si se usa la NumberStyles.AllowHexSpecifier marca , s
debe ser la representación de cadena de un valor hexadecimal sin un prefijo. Por ejemplo, "9AF3" analiza correctamente, pero "0x9AF3" no. Las únicas marcas que pueden estar presentes en style
son NumberStyles.AllowLeadingWhite y NumberStyles.AllowTrailingWhite. (La NumberStyles enumeración tiene un estilo de número compuesto, NumberStyles.HexNumber, que incluye ambas marcas de espacio en blanco).
El provider
parámetro es una IFormatProvider implementación cuyo GetFormat método obtiene un NumberFormatInfo objeto . El NumberFormatInfo objeto proporciona información específica de la referencia cultural sobre el formato de s
. 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:
- Int16.cs
- Source:
- Int16.cs
- Source:
- Int16.cs
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 de 16 bits con signo equivalente.
public static short Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
public static short Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> int16
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As Short
Parámetros
- s
- ReadOnlySpan<Char>
Un intervalo que contiene los caracteres que representan el número que se va a convertir.
- 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
Un IFormatProvider que proporciona información de formato específica de la referencia cultural acerca de s
.
Devoluciones
Entero con signo de 16 bits equivalente al número especificado en s
.
Implementaciones
Se aplica a
Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)
- Source:
- Int16.cs
- Source:
- Int16.cs
Analiza un intervalo de caracteres UTF-8 en un valor.
public static short Parse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> int16
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As Short
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:
- Int16.cs
- Source:
- Int16.cs
- Source:
- Int16.cs
Convierte la representación en forma de cadena de un número en el formato específico de la referencia cultural que se haya especificado en el entero de 16 bits con signo equivalente.
public:
static short Parse(System::String ^ s, IFormatProvider ^ provider);
public:
static short Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<short>::Parse;
public static short Parse (string s, IFormatProvider provider);
public static short Parse (string s, IFormatProvider? provider);
static member Parse : string * IFormatProvider -> int16
Public Shared Function Parse (s As String, provider As IFormatProvider) As Short
Parámetros
- s
- String
Cadena que contiene un número que se va a convertir.
- provider
- IFormatProvider
Un IFormatProvider que proporciona información de formato específica de la referencia cultural acerca de s
.
Devoluciones
Entero con signo de 16 bits equivalente al número especificado en s
.
Implementaciones
Excepciones
s
es null
.
s
no tiene el formato correcto.
s
representa un número menor que Int16.MinValue o mayor que Int16.MaxValue.
Ejemplos
En el ejemplo siguiente se analizan las representaciones de cadena de Int16 valores con el Int16.Parse(String, IFormatProvider) método .
String^ stringToConvert;
Int16 number;
stringToConvert = " 214 ";
try
{
number = Int16::Parse(stringToConvert, CultureInfo::InvariantCulture);
Console::WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException ^e)
{
Console::WriteLine("'{0'} is out of range of the Int16 data type.",
stringToConvert);
}
stringToConvert = " + 214";
try
{
number = Int16::Parse(stringToConvert, CultureInfo::InvariantCulture);
Console::WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException ^e)
{
Console::WriteLine("'{0'} is out of range of the Int16 data type.",
stringToConvert);
}
stringToConvert = " +214 ";
try
{
number = Int16::Parse(stringToConvert, CultureInfo::InvariantCulture);
Console::WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException ^e)
{
Console::WriteLine("'{0'} is out of range of the Int16 data type.",
stringToConvert);
}
// The example displays the following output to the console:
// Converted ' 214 ' to 214.
// Unable to parse ' + 214'.
// Converted ' +214 ' to 214.
string stringToConvert;
short number;
stringToConvert = " 214 ";
try
{
number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture);
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException)
{
Console.WriteLine("'{0'} is out of range of the Int16 data type.",
stringToConvert);
}
stringToConvert = " + 214";
try
{
number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture);
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException)
{
Console.WriteLine("'{0'} is out of range of the Int16 data type.",
stringToConvert);
}
stringToConvert = " +214 ";
try
{
number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture);
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException)
{
Console.WriteLine("'{0'} is out of range of the Int16 data type.",
stringToConvert);
}
// The example displays the following output to the console:
// Converted ' 214 ' to 214.
// Unable to parse ' + 214'.
// Converted ' +214 ' to 214.
let stringToConvert = " 214 "
try
let number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
printfn $"Converted '{stringToConvert}' to {number}."
with
| :? FormatException ->
printfn $"Unable to parse '{stringToConvert}'."
| :? OverflowException ->
printfn $"'{stringToConvert}' is out of range of the Int16 data type."
let stringToConvert = " + 214"
try
let number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
printfn $"Converted '{stringToConvert}' to {number}."
with
| :? FormatException ->
printfn $"Unable to parse '{stringToConvert}'."
| :? OverflowException ->
printfn $"'{stringToConvert}' is out of range of the Int16 data type."
let stringToConvert = " +214 "
try
let number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
printfn $"Converted '{stringToConvert}' to {number}."
with
| :? FormatException ->
printfn $"Unable to parse '{stringToConvert}'."
| :? OverflowException ->
printfn $"'{stringToConvert}' is out of range of the Int16 data type."
// The example displays the following output to the console:
// Converted ' 214 ' to 214.
// Unable to parse ' + 214'.
// Converted ' +214 ' to 214.
Dim stringToConvert As String
Dim number As Short
stringToConvert = " 214 "
Try
number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
Catch e As FormatException
Console.WriteLine("Unable to parse '{0}'.", stringToConvert)
Catch e As OverflowException
Console.WriteLine("'{0'} is out of range of the Int16 data type.", _
stringToConvert)
End Try
stringToConvert = " + 214"
Try
number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
Catch e As FormatException
Console.WriteLine("Unable to parse '{0}'.", stringToConvert)
Catch e As OverflowException
Console.WriteLine("'{0'} is out of range of the Int16 data type.", _
stringToConvert)
End Try
stringToConvert = " +214 "
Try
number = Int16.Parse(stringToConvert, CultureInfo.InvariantCulture)
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
Catch e As FormatException
Console.WriteLine("Unable to parse '{0}'.", stringToConvert)
Catch e As OverflowException
Console.WriteLine("'{0'} is out of range of the Int16 data type.", _
stringToConvert)
End Try
' The example displays the following output to the console:
' Converted ' 214 ' to 214.
' Unable to parse ' + 214'.
' Converted ' +214 ' to 214.
Comentarios
El s
parámetro contiene un número del formulario:
[ws] [sign]digits[ws]
Los elementos de los corchetes ([ y ]) son opcionales. En esta tabla se describe cada elemento.
Elemento | Descripción |
---|---|
ws | Un espacio en blanco opcional. |
sign | Un signo opcional. |
dígitos | Secuencia de dígitos comprendidos entre 0 y 9. |
El s
parámetro se interpreta mediante el NumberStyles.Integer estilo . Además de los dígitos decimales, solo se permiten espacios iniciales y finales junto con un signo inicial en s
. 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 Int16.Parse(String, NumberStyles, IFormatProvider) método .
El provider
parámetro es una IFormatProvider implementación que obtiene un NumberFormatInfo objeto . NumberFormatInfo proporciona información específica de la referencia cultural sobre el formato de s
. Si provider
es null
, se usa para NumberFormatInfo la referencia cultural actual.
Consulte también
Se aplica a
Parse(String)
- Source:
- Int16.cs
- Source:
- Int16.cs
- Source:
- Int16.cs
Convierte la representación en forma de cadena de un número en el entero de 16 bits con signo equivalente.
public:
static short Parse(System::String ^ s);
public static short Parse (string s);
static member Parse : string -> int16
Public Shared Function Parse (s As String) As Short
Parámetros
- s
- String
Cadena que contiene un número que se va a convertir.
Devoluciones
Entero con signo de 16 bits equivalente al número incluido en s
.
Excepciones
s
es null
.
s
no tiene el formato correcto.
s
representa un número menor que Int16.MinValue o mayor que Int16.MaxValue.
Ejemplos
En el ejemplo siguiente se muestra cómo convertir un valor de cadena en un valor entero de 16 bits con signo mediante el Int16.Parse(String) método . A continuación, el valor entero resultante se muestra en la consola.
String^ value;
Int16 number;
value = " 12603 ";
try
{
number = Int16::Parse(value);
Console::WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to convert '{0}' to a 16-bit signed integer.",
value);
}
value = " 16,054";
try
{
number = Int16::Parse(value);
Console::WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to convert '{0}' to a 16-bit signed integer.",
value);
}
value = " -17264";
try
{
number = Int16::Parse(value);
Console::WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to convert '{0}' to a 16-bit signed integer.",
value);
}
// The example displays the following output to the console:
// Converted ' 12603 ' to 12603.
// Unable to convert ' 16,054' to a 16-bit signed integer.
// Converted ' -17264' to -17264.
string value;
short number;
value = " 12603 ";
try
{
number = Int16.Parse(value);
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.",
value);
}
value = " 16,054";
try
{
number = Int16.Parse(value);
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.",
value);
}
value = " -17264";
try
{
number = Int16.Parse(value);
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.",
value);
}
// The example displays the following output to the console:
// Converted ' 12603 ' to 12603.
// Unable to convert ' 16,054' to a 16-bit signed integer.
// Converted ' -17264' to -17264.
let value = " 12603 "
try
let number = Int16.Parse value
printfn $"Converted '{value}' to {number}."
with :? FormatException ->
printfn $"Unable to convert '{value}' to a 16-bit signed integer."
let value = " 16,054"
try
let number = Int16.Parse value
printfn $"Converted '{value}' to {number}."
with :? FormatException ->
printfn "Unable to convert '{value}' to a 16-bit signed integer."
let value = " -17264"
try
let number = Int16.Parse value
printfn $"Converted '{value}' to {number}."
with :? FormatException ->
printfn "Unable to convert '{value}' to a 16-bit signed integer."
// The example displays the following output to the console:
// Converted ' 12603 ' to 12603.
// Unable to convert ' 16,054' to a 16-bit signed integer.
// Converted ' -17264' to -17264.
Dim value As String
Dim number As Short
value = " 12603 "
Try
number = Short.Parse(value)
Console.WriteLine("Converted '{0}' to {1}.", value, number)
Catch e As FormatException
Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.", _
value)
End Try
value = " 16,054"
Try
number = Short.Parse(value)
Console.WriteLine("Converted '{0}' to {1}.", value, number)
Catch e As FormatException
Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.", _
value)
End Try
value = " -17264"
Try
number = Short.Parse(value)
Console.WriteLine("Converted '{0}' to {1}.", value, number)
Catch e As FormatException
Console.WriteLine("Unable to convert '{0}' to a 16-bit signed integer.", _
value)
End Try
' The example displays the following output to the console:
' Converted ' 12603 ' to 12603.
' Unable to convert ' 16,054' to a 16-bit signed integer.
' Converted ' -17264' to -17264.
Comentarios
El s
parámetro contiene un número del formulario:
[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. |
dígitos | Secuencia de dígitos comprendidos entre 0 y 9. |
El s
parámetro se interpreta mediante el NumberStyles.Integer estilo . Además de los dígitos decimales del valor entero, solo se permiten espacios iniciales y finales junto con un signo inicial. Para definir explícitamente los elementos de estilo que pueden estar presentes en s
, use el Int16.Parse(String, NumberStyles) método o Parse .
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 obtener más información, vea CurrentInfo. Para analizar una cadena mediante la información de formato de alguna otra referencia cultural, use o Int16.Parse(String, IFormatProvider) el Int16.Parse(String, NumberStyles, IFormatProvider) método .
Consulte también
Se aplica a
Parse(ReadOnlySpan<Char>, IFormatProvider)
- Source:
- Int16.cs
- Source:
- Int16.cs
- Source:
- Int16.cs
Analiza un intervalo de caracteres en un valor.
public:
static short Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<short>::Parse;
public static short Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> int16
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As Short
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:
- Int16.cs
- Source:
- Int16.cs
Analiza un intervalo de caracteres UTF-8 en un valor.
public:
static short Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<short>::Parse;
public static short Parse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> int16
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As Short
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, NumberStyles)
- Source:
- Int16.cs
- Source:
- Int16.cs
- Source:
- Int16.cs
Convierte la representación en forma de cadena de un número con el estilo especificado en el entero de 16 bits con signo equivalente.
public:
static short Parse(System::String ^ s, System::Globalization::NumberStyles style);
public static short Parse (string s, System.Globalization.NumberStyles style);
static member Parse : string * System.Globalization.NumberStyles -> int16
Public Shared Function Parse (s As String, style As NumberStyles) As Short
Parámetros
- s
- String
Cadena que contiene un número que se va a convertir.
- 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.
Devoluciones
Entero con signo de 16 bits equivalente al número especificado en s
.
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 Int16.MinValue o mayor que Int16.MaxValue.
o bien
s
incluye dígitos fraccionarios distintos de cero.
Ejemplos
En el ejemplo siguiente se usa el Int16.Parse(String, NumberStyles) método para analizar las representaciones de cadena de Int16 valores mediante la referencia cultural en-US.
using namespace System;
using namespace System::Globalization;
ref class ParseSample
{
public:
static void Main()
{
String^ value;
NumberStyles style;
// Parse a number with a thousands separator (throws an exception).
value = "14,644";
style = NumberStyles::None;
ParseSample::ParseToInt16(value, style);
style = NumberStyles::AllowThousands;
ParseToInt16(value, style);
// Parse a number with a thousands separator and decimal point.
value = "14,644.00";
style = NumberStyles::AllowThousands | NumberStyles::Integer |
NumberStyles::AllowDecimalPoint;
ParseToInt16(value, style);
// Parse a number with a fractional component (throws an exception).
value = "14,644.001";
ParseToInt16(value, style);
// Parse a number in exponential notation.
value = "145E02";
style = style | NumberStyles::AllowExponent;
ParseToInt16(value, style);
// Parse a number in exponential notation with a positive sign.
value = "145E+02";
ParseToInt16(value, style);
// Parse a number in exponential notation with a negative sign
// (throws an exception).
value = "145E-02";
ParseToInt16(value, style);
}
private:
static void ParseToInt16(String^ value, NumberStyles style)
{
try
{
Int16 number = Int16::Parse(value, style);
Console::WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException ^e)
{
Console::WriteLine("Unable to parse '{0}' with style {1}.", value,
style);
}
catch (OverflowException ^e)
{
Console::WriteLine("'{0}' is out of range of the Int16 type.", value);
}
}
};
int main()
{
ParseSample::Main();
Console::ReadLine();
return 0;
}
// The example displays the following output:
// Unable to parse '14,644' with style None.
// Converted '14,644' to 14644.
// Converted '14,644.00' to 14644.
// '14,644.001' is out of range of the Int16 type.
// Converted '145E02' to 14500.
// Converted '145E+02' to 14500.
// '145E-02' is out of range of the Int16 type.
using System;
using System.Globalization;
public class ParseSample
{
public static void Main()
{
string value;
NumberStyles style;
// Parse a number with a thousands separator (throws an exception).
value = "14,644";
style = NumberStyles.None;
ParseToInt16(value, style);
style = NumberStyles.AllowThousands;
ParseToInt16(value, style);
// Parse a number with a thousands separator and decimal point.
value = "14,644.00";
style = NumberStyles.AllowThousands | NumberStyles.Integer |
NumberStyles.AllowDecimalPoint;
ParseToInt16(value, style);
// Parse a number with a fractional component (throws an exception).
value = "14,644.001";
ParseToInt16(value, style);
// Parse a number in exponential notation.
value = "145E02";
style = style | NumberStyles.AllowExponent;
ParseToInt16(value, style);
// Parse a number in exponential notation with a positive sign.
value = "145E+02";
ParseToInt16(value, style);
// Parse a number in exponential notation with a negative sign
// (throws an exception).
value = "145E-02";
ParseToInt16(value, style);
}
private static void ParseToInt16(string value, NumberStyles style)
{
try
{
short number = Int16.Parse(value, style);
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse '{0}' with style {1}.", value,
style.ToString());
}
catch (OverflowException)
{
Console.WriteLine("'{0}' is out of range of the Int16 type.", value);
}
}
}
// The example displays the following output to the console:
// Unable to parse '14,644' with style None.
// Converted '14,644' to 14644.
// Converted '14,644.00' to 14644.
// '14,644.001' is out of range of the Int16 type.
// Converted '145E02' to 14500.
// Converted '145E+02' to 14500.
// '145E-02' is out of range of the Int16 type.
open System
open System.Globalization
let parseToInt16 (value: string) (style: NumberStyles) =
try
let number = Int16.Parse(value, style)
printfn $"Converted '{value}' to {number}."
with
| :? FormatException ->
printfn $"Unable to parse '{value}' with style {style}."
| :? OverflowException ->
printfn $"'{value}' is out of range of the Int16 type."
[<EntryPoint>]
let main _ =
// Parse a number with a thousands separator (throws an exception).
let value = "14,644"
let style = NumberStyles.None
parseToInt16 value style
let style = NumberStyles.AllowThousands
parseToInt16 value style
// Parse a number with a thousands separator and decimal point.
let value = "14,644.00"
let style = NumberStyles.AllowThousands ||| NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint
parseToInt16 value style
// Parse a number with a fractional component (throws an exception).
let value = "14,644.001"
parseToInt16 value style
// Parse a number in exponential notation.
let value = "145E02"
let style = style ||| NumberStyles.AllowExponent
parseToInt16 value style
// Parse a number in exponential notation with a positive sign.
let value = "145E+02"
parseToInt16 value style
// Parse a number in exponential notation with a negative sign
// (throws an exception).
let value = "145E-02"
parseToInt16 value style
0
// The example displays the following output to the console:
// Unable to parse '14,644' with style None.
// Converted '14,644' to 14644.
// Converted '14,644.00' to 14644.
// '14,644.001' is out of range of the Int16 type.
// Converted '145E02' to 14500.
// Converted '145E+02' to 14500.
// '145E-02' is out of range of the Int16 type.
Imports System.Globalization
Module ParseSample
Public Sub Main()
Dim value As String
Dim style As NumberStyles
' Parse a number with a thousands separator (throws an exception).
value = "14,644"
style = NumberStyles.None
ParseToInt16(value, style)
style = NumberStyles.AllowThousands
ParseToInt16(value, style)
' Parse a number with a thousands separator and decimal point.
value = "14,644.00"
style = NumberStyles.AllowThousands Or NumberStyles.Integer Or _
NumberStyles.AllowDecimalPoint
ParseToInt16(value, style)
' Parse a number with a fractional component (throws an exception).
value = "14,644.001"
ParseToInt16(value, style)
' Parse a number in exponential notation.
value = "145E02"
style = style Or NumberStyles.AllowExponent
ParseToInt16(value, style)
' Parse a number in exponential notation with a positive sign.
value = "145E+02"
ParseToInt16(value, style)
' Parse a number in exponential notation with a negative sign
' (throws an exception).
value = "145E-02"
ParseToInt16(value, style)
End Sub
Private Sub ParseToInt16(value As String, style As NumberStyles)
Try
Dim number As Short = Int16.Parse(value, style)
Console.WriteLine("Converted '{0}' to {1}.", value, number)
Catch e As FormatException
Console.WriteLine("Unable to parse '{0}' with style {1}.", value, _
style.ToString())
Catch e As OverflowException
Console.WriteLine("'{0}' is out of range of the Int16 type.", value)
End Try
End Sub
End Module
' The example displays the following output to the console:
' Unable to parse '14,644' with style None.
' Converted '14,644' to 14644.
' Converted '14,644.00' to 14644.
' '14,644.001' is out of range of the Int16 type.
' Converted '145E02' to 14500.
' Converted '145E+02' to 14500.
' '145E-02' is out of range of the Int16 type.
Comentarios
El style
parámetro define los elementos de estilo (como espacios en blanco o un símbolo de signo) que se permiten en el s
parámetro para que la operación de análisis se realice correctamente. Debe ser una combinación de marcas de bits de la NumberStyles enumeración . Según el valor de style
, el s
parámetro puede incluir los siguientes elementos:
[ws] [$] [sign] [digits,]digits[.fractional_digits][e[sign]digits][ws]
O bien, si style
incluye AllowHexSpecifier:
[ws]hexdigits[ws]
Los elementos entre corchetes ([ y ]) son opcionales. En esta tabla se describe cada elemento.
Elemento | Descripción |
---|---|
ws | Espacio en blanco opcional. El espacio en blanco puede aparecer al principio de s si incluye la NumberStyles.AllowLeadingWhite marca o al final de s si style incluye la NumberStyles.AllowTrailingWhite marca .style |
$ | Símbolo de moneda específico de la referencia cultural. Su posición en la cadena se define mediante la NumberFormatInfo.CurrencyPositivePattern propiedad y NumberFormatInfo.CurrencyNegativePattern 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 . |
dígitos | Secuencia de dígitos de 0 a 9. |
, | Símbolo separador de miles específico de la referencia cultural. El símbolo separador de miles 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 decimal de la referencia cultural actual puede aparecer en s si style incluye la NumberStyles.AllowDecimalPoint marca . |
fractional_digits | Secuencia del dígito 0. Los dígitos fraccionarios pueden aparecer en s si style incluye la NumberStyles.AllowDecimalPoint marca . Si aparece algún dígito distinto de 0 en fractional_digits, el método produce una OverflowExceptionexcepción . |
e | Carácter "e" o "E", que indica que s se puede representar en notación exponencial. El s parámetro puede representar un número en notación exponencial si style incluye la NumberStyles.AllowExponent marca . Sin embargo, el s parámetro debe representar un número en el intervalo del tipo de Int16 datos y no puede tener un componente fraccionaria distinto de cero. |
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. La mayoría de los miembros restantes NumberStyles controlan los elementos que pueden ser 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 de NumberStyles no compuestos | Elementos permitidos en s además de dígitos |
---|---|
NumberStyles.None | Solo dígitos decimales. |
NumberStyles.AllowDecimalPoint | Los elementos . y fractional_digits . Sin embargo, fractional_digits solo debe constar de uno o varios dígitos o se produce una OverflowException excepción . |
NumberStyles.AllowExponent | El s parámetro también puede usar la notación exponencial. |
NumberStyles.AllowLeadingWhite | Elemento ws al principio de s . |
NumberStyles.AllowTrailingWhite | Elemento ws al final de s . |
NumberStyles.AllowLeadingSign | Un signo puede aparecer antes de los dígitos. |
NumberStyles.AllowTrailingSign | Un signo puede aparecer después de los dígitos. |
NumberStyles.AllowParentheses | Elemento de signo en forma de paréntesis que incluye el valor numérico. |
NumberStyles.AllowThousands | Elemento , . |
NumberStyles.AllowCurrencySymbol | Elemento $. |
Si se usa la NumberStyles.AllowHexSpecifier marca , s
debe ser la representación de cadena de un valor hexadecimal sin prefijo. Por ejemplo, "9AF3" analiza correctamente, pero "0x9AF3" no. Las únicas marcas que pueden estar presentes en style
son NumberStyles.AllowLeadingWhite y NumberStyles.AllowTrailingWhite. (La NumberStyles enumeración tiene un estilo de número compuesto, NumberStyles.HexNumber, que incluye ambas marcas de espacio en blanco).
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 obtener más información, vea NumberFormatInfo.CurrentInfo. Para analizar s
mediante la información de formato de una referencia cultural específica, llame al Int16.Parse(String, NumberStyles, IFormatProvider) método .
Consulte también
Se aplica a
Comentaris
https://aka.ms/ContentUserFeedback.
Properament: al llarg del 2024 eliminarem gradualment GitHub Issues com a mecanisme de retroalimentació del contingut i el substituirem per un nou sistema de retroalimentació. Per obtenir més informació, consulteu:Envieu i consulteu els comentaris de