Int16.Parse Метод
Определение
Преобразует строковое представление числа в эквивалентное ему 16-битовое целое число со знаком.Converts the string representation of a number to its 16-bit signed integer equivalent.
Перегрузки
Parse(String, NumberStyles, IFormatProvider) |
Преобразует строковое представление числа в формате, соответствующем языку и региональным параметрам, в эквивалентное ему 16-битовое целое число со знаком.Converts the string representation of a number in a specified style and culture-specific format to its 16-bit signed integer equivalent. |
Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) |
Преобразует представление числа в виде диапазона в указанном стиле и формате, соответствующем языку и региональным параметрам, в эквивалентное ему 16-битовое целое число со знаком.Converts the span representation of a number in a specified style and culture-specific format to its 16-bit signed integer equivalent. |
Parse(String, NumberStyles) |
Преобразует строковое представление числа в указанном формате в эквивалентное ему 16-битовое целое число со знаком.Converts the string representation of a number in a specified style to its 16-bit signed integer equivalent. |
Parse(String) |
Преобразует строковое представление числа в эквивалентное ему 16-битовое целое число со знаком.Converts the string representation of a number to its 16-bit signed integer equivalent. |
Parse(String, IFormatProvider) |
Преобразует строковое представление числа в указанном формате, соответствующем языку и региональным параметрам, в эквивалентное ему 16-битовое целое число со знаком.Converts the string representation of a number in a specified culture-specific format to its 16-bit signed integer equivalent. |
Parse(String, NumberStyles, IFormatProvider)
Преобразует строковое представление числа в формате, соответствующем языку и региональным параметрам, в эквивалентное ему 16-битовое целое число со знаком.Converts the string representation of a number in a specified style and culture-specific format to its 16-bit signed integer equivalent.
public:
static short Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
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
Параметры
- s
- String
Строка, содержащая преобразуемое число.A string containing a number to convert.
- style
- NumberStyles
Побитовое сочетание значений перечисления, обозначающих элементы стиля, которые могут быть представлены в параметре s
.A bitwise combination of enumeration values that indicates the style elements that can be present in s
. Обычно указывается значение Integer.A typical value to specify is Integer.
- provider
- IFormatProvider
Интерфейс IFormatProvider предоставляет сведения о форматировании параметра s
для соответствующего языка и региональных параметров.An IFormatProvider that supplies culture-specific formatting information about s
.
Возвращаемое значение
16-разрядное целое число со знаком, эквивалентное числу, заданному в параметре s
.A 16-bit signed integer equivalent to the number specified in s
.
Исключения
s
имеет значение null
.s
is null
.
style
не является значением NumberStyles.style
is not a NumberStyles value.
-или--or-
style
не является сочетанием значений AllowHexSpecifier и HexNumber.style
is not a combination of AllowHexSpecifier and HexNumber values.
s
не представлен в формате, совместимом с style
.s
is not in a format compliant with style
.
s
представляет число, которое меньше значения MinValue или больше значения MaxValue.s
represents a number less than MinValue or greater than MaxValue.
-или--or-
s
содержит ненулевые дробные цифры.s
includes non-zero fractional digits.
Примеры
В следующем примере используются различные style
provider
Параметры и для анализа строковых представлений Int16 значений.The following example uses a variety of style
and provider
parameters to parse the string representations of Int16 values.
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.
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.
Комментарии
style
Параметр определяет элементы стиля (например, пробелы или положительные знаки), которые разрешены в s
параметре для успешной операции синтаксического анализа.The style
parameter defines the style elements (such as white space or the positive sign) that are allowed in the s
parameter for the parse operation to succeed. Он должен представлять собой сочетание битовых флагов из NumberStyles перечисления.It must be a combination of bit flags from the NumberStyles enumeration. В зависимости от значения style
s
параметр может включать следующие элементы:Depending on the value of style
, the s
parameter may include the following elements:
Протокол [$] писать [цифры,] цифры [.fractional_digits] [e [знак] цифры] [ws][ws][$][sign][digits,]digits[.fractional_digits][e[sign]digits][ws]
Или, если style
включает AllowHexSpecifier :Or, if style
includes AllowHexSpecifier:
[ws] хексдигитс [ws][ws]hexdigits[ws]
Элементы в квадратных скобках ([и]) являются необязательными.Elements in square brackets ([ and ]) are optional. Каждый из элементов описан в таблице ниже.The following table describes each element.
ЭлементElement | ОписаниеDescription |
---|---|
wsws | Необязательный пробел.Optional white space. Пробелы могут присутствовать в начале s , если style включает NumberStyles.AllowLeadingWhite флаг, или в конце, s Если style включает NumberStyles.AllowTrailingWhite флаг.White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag, or at the end of s if style includes the NumberStyles.AllowTrailingWhite flag. |
$ | Символ валюты, зависящий от языка и региональных параметров.A culture-specific currency symbol. Его расположение в строке определяется NumberFormatInfo.CurrencyPositivePattern NumberFormatInfo.CurrencyNegativePattern свойством и текущего языка и региональных параметров.Its position in the string is defined by the NumberFormatInfo.CurrencyPositivePattern and NumberFormatInfo.CurrencyNegativePattern property of the current culture. Символ валюты текущего языка и региональных параметров может отображаться в, s Если style включает NumberStyles.AllowCurrencySymbol флаг.The current culture's currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag. |
signsign | Необязательный знак.An optional sign. Знак может присутствовать в начале s style , если включает NumberStyles.AllowLeadingSign флаг, и может находиться в конце, s Если style включает NumberStyles.AllowTrailingSign флаг.The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingSign flag. Круглые скобки могут использоваться в s , чтобы указать отрицательное значение, если style включает NumberStyles.AllowParentheses флаг.Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag. |
digitsdigits | Последовательность цифр от 0 до 9.A sequence of digits from 0 through 9. |
,, | Символ разделителя тысяч, зависящий от языка и региональных параметров.A culture-specific thousands separator symbol. Символ разделителя тысяч текущего языка и региональных параметров может отображаться в, s Если style включает NumberStyles.AllowThousands флаг.The current culture's thousands separator symbol can appear in s if style includes the NumberStyles.AllowThousands flag. |
.. | Символ десятичной запятой, зависящий от языка и региональных параметров.A culture-specific decimal point symbol. Символ десятичной запятой текущего языка и региональных параметров может присутствовать в, s Если style включает NumberStyles.AllowDecimalPoint флаг.The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag. |
fractional_digitsfractional_digits | Последовательность 0 цифр.A sequence of the 0 digit. Дробные цифры могут присутствовать s в style , если включает NumberStyles.AllowDecimalPoint флаг.Fractional digits can appear in s if style includes the NumberStyles.AllowDecimalPoint flag. Если в fractional_digits отображается любая цифра, отличная от 0, метод создает исключение OverflowException .If any digit other than 0 appears in fractional_digits , the method throws an OverflowException. |
ee | Символ "e" или "E", который указывает, что s может быть представлено в экспоненциальной нотации.The 'e' or 'E' character, which indicates that s can be represented in exponential notation. s Параметр может представлять число в экспоненциальной нотации style , если включает NumberStyles.AllowExponent флаг.The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag. Однако s параметр должен представлять число в диапазоне Int16 типа данных и не может иметь дробный компонент, не равный нулю.However, the s parameter must represent a number in the range of the Int16 data type and cannot have a non-zero fractional component. |
хексдигитсhexdigits | Последовательность шестнадцатеричных цифр от 0 до f или от 0 до F.A sequence of hexadecimal digits from 0 through f, or 0 through F. |
Примечание
Все завершающие символы NUL (U + 0000) в s
игнорируются операцией синтаксического анализа, независимо от значения style
аргумента.Any terminating NUL (U+0000) characters in s
are ignored by the parsing operation, regardless of the value of the style
argument.
Строка с цифрами (которая соответствует NumberStyles.None стилю) всегда будет успешно проанализирована.A string with digits only (which corresponds to the NumberStyles.None style) always parses successfully. Большинство оставшихся элементов NumberStyles управляют элементами, которые могут быть, но не должны присутствовать в этой входной строке.Most of the remaining NumberStyles members control elements that may be but are not required to be present in this input string. В следующей таблице показано, как отдельные NumberStyles члены влияют на элементы, которые могут присутствовать в s
.The following table indicates how individual NumberStyles members affect the elements that may be present in s
.
Несоставные значения NumberStylesNon-composite NumberStyles values | Элементы, разрешенные в s в дополнение к цифрамElements permitted in s in addition to digits |
---|---|
NumberStyles.None | Только десятичные цифры.Decimal digits only. |
NumberStyles.AllowDecimalPoint | Языковой элемент .The . и fractional_digits элементы.and fractional_digits elements. Однако fractional_digits должны состоять только из одной или более цифр 0 или OverflowException выдается исключение.However, fractional_digits must consist of only one or more 0 digits or an OverflowException is thrown. |
NumberStyles.AllowExponent | s Параметр также может использовать экспоненциальную нотацию.The s parameter can also use exponential notation. |
NumberStyles.AllowLeadingWhite | Элемент WS в начале s .The ws element at the beginning of s . |
NumberStyles.AllowTrailingWhite | Элемент WS в конце s .The ws element at the end of s . |
NumberStyles.AllowLeadingSign | Знак может располагаться перед цифрами.A sign can appear before digits. |
NumberStyles.AllowTrailingSign | Знак может располагаться после цифр.A sign can appear after digits. |
NumberStyles.AllowParentheses | Элемент Sign в виде круглых скобок, охватывающих числовое значение.The sign element in the form of parentheses enclosing the numeric value. |
NumberStyles.AllowThousands | Элемент , .The , element. |
NumberStyles.AllowCurrencySymbol | $ Элемент.The $ element. |
Если NumberStyles.AllowHexSpecifier используется флаг, то параметр s
должен быть строковым представлением шестнадцатеричного значения без префикса.If the NumberStyles.AllowHexSpecifier flag is used, s
must be the string representation of a hexadecimal value without a prefix. Например, "9AF3" успешно анализируется, но "0x9AF3" — нет.For example, "9AF3" parses successfully, but "0x9AF3" does not.. Единственными другими флагами, которые могут присутствовать в style
, являются NumberStyles.AllowLeadingWhite и NumberStyles.AllowTrailingWhite .The only other flags that can be present in style
are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. ( NumberStyles Перечисление имеет стиль составного числа, NumberStyles.HexNumber включающий оба флага пробела.)(The NumberStyles enumeration has a composite number style, NumberStyles.HexNumber, that includes both white space flags.)
provider
Параметр — это IFormatProvider реализация, GetFormat метод которой получает NumberFormatInfo объект.The provider
parameter is an IFormatProvider implementation whose GetFormat method obtains a NumberFormatInfo object. NumberFormatInfoОбъект предоставляет сведения о формате для конкретного языка и региональных параметров s
.The NumberFormatInfo object provides culture-specific information about the format of s
. Если provider
параметр имеет значение null
, NumberFormatInfo используется объект для текущего языка и региональных параметров.If provider
is null
, the NumberFormatInfo object for the current culture is used.
См. также раздел
Применяется к
Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)
Преобразует представление числа в виде диапазона в указанном стиле и формате, соответствующем языку и региональным параметрам, в эквивалентное ему 16-битовое целое число со знаком.Converts the span representation of a number in a specified style and culture-specific format to its 16-bit signed integer equivalent.
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
Параметры
- s
- ReadOnlySpan<Char>
Диапазон, содержащий символы, которые представляют преобразуемое число.A span containing the characters representing the number to convert.
- style
- NumberStyles
Побитовое сочетание значений перечисления, обозначающих элементы стиля, которые могут быть представлены в параметре s
.A bitwise combination of enumeration values that indicates the style elements that can be present in s
. Обычно указывается значение Integer.A typical value to specify is Integer.
- provider
- IFormatProvider
Интерфейс IFormatProvider предоставляет сведения о форматировании параметра s
для соответствующего языка и региональных параметров.An IFormatProvider that supplies culture-specific formatting information about s
.
Возвращаемое значение
16-разрядное целое число со знаком, эквивалентное числу, заданному в параметре s
.A 16-bit signed integer equivalent to the number specified in s
.
Применяется к
Parse(String, NumberStyles)
Преобразует строковое представление числа в указанном формате в эквивалентное ему 16-битовое целое число со знаком.Converts the string representation of a number in a specified style to its 16-bit signed integer equivalent.
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
Параметры
- s
- String
Строка, содержащая преобразуемое число.A string containing a number to convert.
- style
- NumberStyles
Побитовое сочетание значений перечисления, обозначающих элементы стиля, которые могут быть представлены в параметре s
.A bitwise combination of the enumeration values that indicates the style elements that can be present in s
. Обычно указывается значение Integer.A typical value to specify is Integer.
Возвращаемое значение
16-разрядное целое число со знаком, эквивалентное числу, заданному в параметре s
.A 16-bit signed integer equivalent to the number specified in s
.
Исключения
s
имеет значение null
.s
is null
.
style
не является значением NumberStyles.style
is not a NumberStyles value.
-или--or-
style
не является сочетанием значений AllowHexSpecifier и HexNumber.style
is not a combination of AllowHexSpecifier and HexNumber values.
s
не представлен в формате, совместимом с style
.s
is not in a format compliant with style
.
s
представляет число, которое меньше значения MinValue или больше значения MaxValue.s
represents a number less than MinValue or greater than MaxValue.
-или--or-
s
содержит ненулевые дробные цифры.s
includes non-zero fractional digits.
Примеры
В следующем примере метод используется Int16.Parse(String, NumberStyles) для анализа строковых представлений Int16 значений с помощью языка и региональных параметров en-US.The following example uses the Int16.Parse(String, NumberStyles) method to parse the string representations of Int16 values using the en-US culture.
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.
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.
Комментарии
style
Параметр определяет элементы стиля (например, пробелы или символы знака), которые разрешены в s
параметре для выполнения операции синтаксического анализа.The style
parameter defines the style elements (such as white space or a sign symbol) that are allowed in the s
parameter for the parse operation to succeed. Он должен представлять собой сочетание битовых флагов из NumberStyles перечисления.It must be a combination of bit flags from the NumberStyles enumeration. В зависимости от значения style
s
параметр может включать следующие элементы:Depending on the value of style
, the s
parameter may include the following elements:
Протокол [$] писать [цифры,] цифры [.fractional_digits] [e [знак] цифры] [ws][ws][$][sign][digits,]digits[.fractional_digits][e[sign]digits][ws]
Или, если style
включает AllowHexSpecifier :Or, if style
includes AllowHexSpecifier:
[ws] хексдигитс [ws][ws]hexdigits[ws]
Элементы в квадратных скобках ([и]) являются необязательными.Items in square brackets ([ and ]) are optional. Каждый из элементов описан в таблице ниже.The following table describes each element.
ЭлементElement | ОписаниеDescription |
---|---|
wsws | Необязательный пробел.Optional white space. Пробелы могут присутствовать в начале s , если style включает NumberStyles.AllowLeadingWhite флаг, или в конце, s Если style включает NumberStyles.AllowTrailingWhite флаг.White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag, or at the end of s if style includes the NumberStyles.AllowTrailingWhite flag. |
$ | Символ валюты, зависящий от языка и региональных параметров.A culture-specific currency symbol. Его расположение в строке определяется NumberFormatInfo.CurrencyPositivePattern NumberFormatInfo.CurrencyNegativePattern свойством и текущего языка и региональных параметров.Its position in the string is defined by the NumberFormatInfo.CurrencyPositivePattern and NumberFormatInfo.CurrencyNegativePattern property of the current culture. Символ валюты текущего языка и региональных параметров может отображаться в, s Если style включает NumberStyles.AllowCurrencySymbol флаг.The current culture's currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag. |
signsign | Необязательный знак.An optional sign. Знак может присутствовать в начале s style , если включает NumberStyles.AllowLeadingSign флаг, и может находиться в конце, s Если style включает NumberStyles.AllowTrailingSign флаг.The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingSign flag. Круглые скобки могут использоваться в s , чтобы указать отрицательное значение, если style включает NumberStyles.AllowParentheses флаг.Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag. |
digitsdigits | Последовательность цифр от 0 до 9.A sequence of digits from 0 through 9. |
,, | Символ разделителя тысяч, зависящий от языка и региональных параметров.A culture-specific thousands separator symbol. Символ разделителя тысяч текущего языка и региональных параметров может отображаться в, s Если style включает NumberStyles.AllowThousands флаг.The current culture's thousands separator symbol can appear in s if style includes the NumberStyles.AllowThousands flag. |
.. | Символ десятичной запятой, зависящий от языка и региональных параметров.A culture-specific decimal point symbol. Символ десятичной запятой текущего языка и региональных параметров может присутствовать в, s Если style включает NumberStyles.AllowDecimalPoint флаг.The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag. |
fractional_digitsfractional_digits | Последовательность 0 цифр.A sequence of the 0 digit. Дробные цифры могут присутствовать s в style , если включает NumberStyles.AllowDecimalPoint флаг.Fractional digits can appear in s if style includes the NumberStyles.AllowDecimalPoint flag. Если в fractional_digits отображается любая цифра, отличная от 0, метод создает исключение OverflowException .If any digit other than 0 appears in fractional_digits , the method throws an OverflowException. |
ee | Символ "e" или "E", который указывает, что s может быть представлено в экспоненциальной нотации.The 'e' or 'E' character, which indicates that s can be represented in exponential notation. s Параметр может представлять число в экспоненциальной нотации style , если включает NumberStyles.AllowExponent флаг.The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag. Однако s параметр должен представлять число в диапазоне Int16 типа данных и не может иметь дробный компонент, не равный нулю.However, the s parameter must represent a number in the range of the Int16 data type and cannot have a non-zero fractional component. |
хексдигитсhexdigits | Последовательность шестнадцатеричных цифр от 0 до f или от 0 до F.A sequence of hexadecimal digits from 0 through f, or 0 through F. |
Примечание
Все завершающие символы NUL (U + 0000) в s
игнорируются операцией синтаксического анализа, независимо от значения style
аргумента.Any terminating NUL (U+0000) characters in s
are ignored by the parsing operation, regardless of the value of the style
argument.
Строка с цифрами (которая соответствует NumberStyles.None стилю) всегда будет успешно проанализирована.A string with digits only (which corresponds to the NumberStyles.None style) always parses successfully. Большинство оставшихся элементов NumberStyles управляют элементами, которые могут быть, но не должны присутствовать в этой входной строке.Most of the remaining NumberStyles members control elements that may be but are not required to be present in this input string. В следующей таблице показано, как отдельные NumberStyles члены влияют на элементы, которые могут присутствовать в s
.The following table indicates how individual NumberStyles members affect the elements that may be present in s
.
Несоставные значения NumberStylesNon-composite NumberStyles values | Элементы, разрешенные в s в дополнение к цифрамElements permitted in s in addition to digits |
---|---|
NumberStyles.None | Только десятичные цифры.Decimal digits only. |
NumberStyles.AllowDecimalPoint | Языковой элемент .The . и fractional_digits элементы.and fractional_digits elements. Однако fractional_digits должны состоять только из одной или более цифр 0 или OverflowException выдается исключение.However, fractional_digits must consist of only one or more 0 digits or an OverflowException is thrown. |
NumberStyles.AllowExponent | s Параметр также может использовать экспоненциальную нотацию.The s parameter can also use exponential notation. |
NumberStyles.AllowLeadingWhite | Элемент WS в начале s .The ws element at the beginning of s . |
NumberStyles.AllowTrailingWhite | Элемент WS в конце s .The ws element at the end of s . |
NumberStyles.AllowLeadingSign | Знак может располагаться перед цифрами.A sign can appear before digits. |
NumberStyles.AllowTrailingSign | Знак может располагаться после цифр.A sign can appear after digits. |
NumberStyles.AllowParentheses | Элемент Sign в виде круглых скобок, охватывающих числовое значение.The sign element in the form of parentheses enclosing the numeric value. |
NumberStyles.AllowThousands | Элемент , .The , element. |
NumberStyles.AllowCurrencySymbol | $ Элемент.The $ element. |
Если NumberStyles.AllowHexSpecifier используется флаг, то параметр s
должен быть строковым представлением шестнадцатеричного значения без префикса.If the NumberStyles.AllowHexSpecifier flag is used, s
must be the string representation of a hexadecimal value without a prefix. Например, "9AF3" успешно анализируется, но "0x9AF3" — нет.For example, "9AF3" parses successfully, but "0x9AF3" does not. Единственными другими флагами, которые могут присутствовать в style
, являются NumberStyles.AllowLeadingWhite и NumberStyles.AllowTrailingWhite .The only other flags that can be present in style
are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. ( NumberStyles Перечисление имеет стиль составного числа, NumberStyles.HexNumber включающий оба флага пробела.)(The NumberStyles enumeration has a composite number style, NumberStyles.HexNumber, that includes both white space flags.)
s
Параметр анализируется с помощью сведений о форматировании в NumberFormatInfo объекте, инициализированном для текущего языка и региональных параметров системы.The s
parameter is parsed using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. Для получения дополнительной информации см. NumberFormatInfo.CurrentInfo.For more information, see NumberFormatInfo.CurrentInfo. Чтобы выполнить синтаксический анализ s
с использованием сведений о форматировании определенного языка и региональных параметров, вызовите Int16.Parse(String, NumberStyles, IFormatProvider) метод.To parse s
using the formatting information of a specific culture, call the Int16.Parse(String, NumberStyles, IFormatProvider) method.
См. также раздел
- NumberStyles
- ToString()
- TryParse
- Синтаксический анализ числовых строк в .NETParsing Numeric Strings in .NET
Применяется к
Parse(String)
Преобразует строковое представление числа в эквивалентное ему 16-битовое целое число со знаком.Converts the string representation of a number to its 16-bit signed integer equivalent.
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
Параметры
- s
- String
Строка, содержащая преобразуемое число.A string containing a number to convert.
Возвращаемое значение
16-разрядное целое число со знаком, эквивалентное числу, содержащемуся в параметре s
.A 16-bit signed integer equivalent to the number contained in s
.
Исключения
s
имеет значение null
.s
is null
.
s
имеет неправильный формат.s
is not in the correct format.
s
представляет число, которое меньше значения MinValue или больше значения MaxValue.s
represents a number less than MinValue or greater than MaxValue.
Примеры
В следующем примере показано, как преобразовать строковое значение в 16-разрядное целое число со знаком с помощью Int16.Parse(String) метода.The following example demonstrates how to convert a string value into a 16-bit signed integer value using the Int16.Parse(String) method. Полученное целочисленное значение затем отображается в консоли.The resulting integer value is then displayed to the console.
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.
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.
Комментарии
s
Параметр содержит номер формы:The s
parameter contains a number of the form:
Протокол [знак] цифры [ws][ws][sign]digits[ws]
Элементы в квадратных скобках ([и]) являются необязательными.Elements in square brackets ([ and ]) are optional. Каждый из элементов описан в таблице ниже.The following table describes each element.
ЭлементElement | ОписаниеDescription |
---|---|
wsws | Необязательный пробел.Optional white space. |
signsign | Необязательный знак.An optional sign. |
digitsdigits | Последовательность цифр в диапазоне от 0 до 9.A sequence of digits ranging from 0 to 9. |
s
Параметр интерпретируется с использованием NumberStyles.Integer стиля.The s
parameter is interpreted using the NumberStyles.Integer style. Помимо десятичных цифр целочисленного значения, допускается только начальные и конечные пробелы, а также ведущий символ.In addition to the integer value's decimal digits, only leading and trailing spaces together with a leading sign are allowed. Чтобы явно определить элементы стиля, которые могут присутствовать в s
, используйте либо Int16.Parse(String, NumberStyles) метод, либо Parse .To explicitly define the style elements that can be present in s
, use either the Int16.Parse(String, NumberStyles) or the Parse method.
s
Параметр анализируется с помощью сведений о форматировании в NumberFormatInfo объекте, инициализированном для текущего языка и региональных параметров системы.The s
parameter is parsed using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. Для получения дополнительной информации см. CurrentInfo.For more information, see CurrentInfo. Чтобы выполнить синтаксический анализ строки, используя сведения о форматировании другого языка и региональных параметров, используйте Int16.Parse(String, IFormatProvider) Int16.Parse(String, NumberStyles, IFormatProvider) метод или.To parse a string using the formatting information of some other culture, use the Int16.Parse(String, IFormatProvider) or the Int16.Parse(String, NumberStyles, IFormatProvider) method.
См. также раздел
Применяется к
Parse(String, IFormatProvider)
Преобразует строковое представление числа в указанном формате, соответствующем языку и региональным параметрам, в эквивалентное ему 16-битовое целое число со знаком.Converts the string representation of a number in a specified culture-specific format to its 16-bit signed integer equivalent.
public:
static short Parse(System::String ^ s, IFormatProvider ^ provider);
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
Параметры
- s
- String
Строка, содержащая преобразуемое число.A string containing a number to convert.
- provider
- IFormatProvider
Интерфейс IFormatProvider предоставляет сведения о форматировании параметра s
для соответствующего языка и региональных параметров.An IFormatProvider that supplies culture-specific formatting information about s
.
Возвращаемое значение
16-разрядное целое число со знаком, эквивалентное числу, заданному в параметре s
.A 16-bit signed integer equivalent to the number specified in s
.
Исключения
s
имеет значение null
.s
is null
.
s
имеет неправильный формат.s
is not in the correct format.
s
представляет число, которое меньше значения MinValue или больше значения MaxValue.s
represents a number less than MinValue or greater than MaxValue.
Примеры
В следующем примере выполняется синтаксический анализ строковых представлений Int16 значений с помощью Int16.Parse(String, IFormatProvider) метода.The following example parses string representations of Int16 values with the Int16.Parse(String, IFormatProvider) method.
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.
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.
Комментарии
s
Параметр содержит номер формы:The s
parameter contains a number of the form:
Протокол [знак] цифры [ws][ws][sign]digits[ws]
Элементы в квадратных скобках ([и]) являются необязательными.Elements in square brackets ([ and ]) are optional. Каждый из элементов описан в таблице ниже.The following table describes each element.
ЭлементElement | ОписаниеDescription |
---|---|
wsws | Необязательный пробел.An optional white space. |
signsign | Необязательный знак.An optional sign. |
digitsdigits | Последовательность цифр в диапазоне от 0 до 9.A sequence of digits ranging from 0 to 9. |
s
Параметр интерпретируется с использованием NumberStyles.Integer стиля.The s
parameter is interpreted using the NumberStyles.Integer style. В дополнение к десятичным цифрам в допускается использование только ведущих и конечных пробелов вместе со знаком в начале s
.In addition to decimal digits, only leading and trailing spaces together with a leading sign are allowed in s
. Чтобы явно определить элементы стиля вместе с данными форматирования, зависящими от языка и региональных параметров, которые могут присутствовать в s
, используйте Int16.Parse(String, NumberStyles, IFormatProvider) метод.To explicitly define the style elements together with the culture-specific formatting information that can be present in s
, use the Int16.Parse(String, NumberStyles, IFormatProvider) method.
provider
Параметр — это IFormatProvider реализация, которая получает NumberFormatInfo объект.The provider
parameter is an IFormatProvider implementation that obtains a NumberFormatInfo object. NumberFormatInfoПредоставляет сведения о формате для конкретного языка и региональных параметров s
.The NumberFormatInfo provides culture-specific information about the format of s
. Если provider
имеет значение null
, NumberFormatInfo используется для текущего языка и региональных параметров.If provider
is null
, the NumberFormatInfo for the current culture is used.