Int32.Parse 方法

定义

将数字的字符串表示形式转换为它的等效 32 位有符号整数。Converts the string representation of a number to its 32-bit signed integer equivalent.

重载

Parse(String, NumberStyles, IFormatProvider)

将指定样式和区域性特定格式的数字的字符串表示形式转换为它的等效 32 位有符号整数。Converts the string representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

将指定样式和区域性特定格式的数字的范围表示形式转换为其等效的 32 位带符号整数。Converts the span representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent.

Parse(String, NumberStyles)

将指定样式的数字的字符串表示形式转换为它的等效 32 位有符号整数。Converts the string representation of a number in a specified style to its 32-bit signed integer equivalent.

Parse(String)

将数字的字符串表示形式转换为它的等效 32 位有符号整数。Converts the string representation of a number to its 32-bit signed integer equivalent.

Parse(String, IFormatProvider)

将指定的区域性特定格式的数字的字符串表示形式转换为它的等效 32 位有符号整数。Converts the string representation of a number in a specified culture-specific format to its 32-bit signed integer equivalent.

Parse(String, NumberStyles, IFormatProvider)

将指定样式和区域性特定格式的数字的字符串表示形式转换为它的等效 32 位有符号整数。Converts the string representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent.

public:
 static int Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public static int Parse (string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static int Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> int
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As Integer

参数

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. 要指定的一个典型值为 IntegerA typical value to specify is Integer.

provider
IFormatProvider

一个对象,用于提供有关 s 格式的区域性特定信息。An object that supplies culture-specific information about the format of s.

返回

Int32

s 中指定的数字等效的 32 位带符号整数。A 32-bit signed integer equivalent to the number specified in s.

例外

snulls is null.

style 不是 NumberStyles 值。style is not a NumberStyles value.

- 或 --or- style 不是 AllowHexSpecifierHexNumber 值的组合。style is not a combination of AllowHexSpecifier and HexNumber values.

s 的格式不符合 styles 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.

示例

下面的示例使用各种 styleprovider 参数来分析值的字符串表示形式 Int32The following example uses a variety of style and provider parameters to parse the string representations of Int32 values. 它还说明了根据用于分析操作的格式设置信息的区域性,可解释相同字符串的一些不同方法。It also illustrates some of the different ways the same string can be interpreted depending on the culture whose formatting information is used for the parsing operation.

using namespace System;
using namespace System::Globalization;

public ref class ParseInt32
{
public:
   static void Main()
   {
      Convert("12,000", NumberStyles::Float | NumberStyles::AllowThousands, 
              gcnew CultureInfo("en-GB"));
      Convert("12,000", NumberStyles::Float | NumberStyles::AllowThousands,
              gcnew CultureInfo("fr-FR"));
      Convert("12,000", NumberStyles::Float, gcnew CultureInfo("en-US"));

      Convert("12 425,00", NumberStyles::Float | NumberStyles::AllowThousands,
              gcnew CultureInfo("sv-SE"));
      Convert("12,425.00", NumberStyles::Float | NumberStyles::AllowThousands,
              NumberFormatInfo::InvariantInfo);
      Convert("631,900", NumberStyles::Integer | NumberStyles::AllowDecimalPoint, 
              gcnew CultureInfo("fr-FR"));
      Convert("631,900", NumberStyles::Integer | NumberStyles::AllowDecimalPoint,
              gcnew CultureInfo("en-US"));
      Convert("631,900", NumberStyles::Integer | NumberStyles::AllowThousands,
              gcnew CultureInfo("en-US"));
   }

private:
   static void Convert(String^ value, NumberStyles style,
                               IFormatProvider^ provider)
   {
      try
      {
         int number = Int32::Parse(value, style, provider);
         Console::WriteLine("Converted '{0}' to {1}.", value, number);
      }
      catch (FormatException^)
      {
         Console::WriteLine("Unable to convert '{0}'.", value);
      }
      catch (OverflowException^)
      {
         Console::WriteLine("'{0}' is out of range of the Int32 type.", value);   
      }
   }                               
};

int main()
{
    ParseInt32::Main();
}
// This example displays the following output to the console:
//       Converted '12,000' to 12000.
//       Converted '12,000' to 12.
//       Unable to convert '12,000'.
//       Converted '12 425,00' to 12425.
//       Converted '12,425.00' to 12425.
//       '631,900' is out of range of the Int32 type.
//       Unable to convert '631,900'.
//       Converted '631,900' to 631900.
using System;
using System.Globalization;

public class ParseInt32
{
   public static void Main()
   {
      Convert("12,000", NumberStyles.Float | NumberStyles.AllowThousands,
              new CultureInfo("en-GB"));
      Convert("12,000", NumberStyles.Float | NumberStyles.AllowThousands,
              new CultureInfo("fr-FR"));
      Convert("12,000", NumberStyles.Float, new CultureInfo("en-US"));

      Convert("12 425,00", NumberStyles.Float | NumberStyles.AllowThousands,
              new CultureInfo("sv-SE"));
      Convert("12,425.00", NumberStyles.Float | NumberStyles.AllowThousands,
              NumberFormatInfo.InvariantInfo);
      Convert("631,900", NumberStyles.Integer | NumberStyles.AllowDecimalPoint,
              new CultureInfo("fr-FR"));
      Convert("631,900", NumberStyles.Integer | NumberStyles.AllowDecimalPoint,
              new CultureInfo("en-US"));
      Convert("631,900", NumberStyles.Integer | NumberStyles.AllowThousands,
              new CultureInfo("en-US"));
   }

   private static void Convert(string value, NumberStyles style,
                               IFormatProvider provider)
   {
      try
      {
         int number = Int32.Parse(value, style, provider);
         Console.WriteLine("Converted '{0}' to {1}.", value, number);
      }
      catch (FormatException)
      {
         Console.WriteLine("Unable to convert '{0}'.", value);
      }
      catch (OverflowException)
      {
         Console.WriteLine("'{0}' is out of range of the Int32 type.", value);
      }
   }
}
// This example displays the following output to the console:
//       Converted '12,000' to 12000.
//       Converted '12,000' to 12.
//       Unable to convert '12,000'.
//       Converted '12 425,00' to 12425.
//       Converted '12,425.00' to 12425.
//       '631,900' is out of range of the Int32 type.
//       Unable to convert '631,900'.
//       Converted '631,900' to 631900.
Imports System.Globalization

Module ParseInt32
   Public Sub Main()
      Convert("12,000", NumberStyles.Float Or NumberStyles.AllowThousands, _
              New CultureInfo("en-GB"))      
      Convert("12,000", NumberStyles.Float Or NumberStyles.AllowThousands, _
              New CultureInfo("fr-FR"))
      Convert("12,000", NumberStyles.Float, New CultureInfo("en-US"))
      
      Convert("12 425,00", NumberStyles.Float Or NumberStyles.AllowThousands, _
              New CultureInfo("sv-SE")) 
      Convert("12,425.00", NumberStyles.Float Or NumberStyles.AllowThousands, _
              NumberFormatInfo.InvariantInfo) 
      Convert("631,900", NumberStyles.Integer Or NumberStyles.AllowDecimalPoint, _ 
              New CultureInfo("fr-FR"))
      Convert("631,900", NumberStyles.Integer Or NumberStyles.AllowDecimalPoint, _
              New CultureInfo("en-US"))
      Convert("631,900", NumberStyles.Integer Or NumberStyles.AllowThousands, _
              New CultureInfo("en-US"))
   End Sub

   Private Sub Convert(value As String, style As NumberStyles, _
                       provider As IFormatProvider)
      Try
         Dim number As Integer = Int32.Parse(value, style, provider)
         Console.WriteLine("Converted '{0}' to {1}.", value, number)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", value)
      Catch e As OverflowException
         Console.WriteLine("'{0}' is out of range of the Int32 type.", value)   
      End Try
   End Sub                       
End Module
' This example displays the following output to the console:
'       Converted '12,000' to 12000.
'       Converted '12,000' to 12.
'       Unable to convert '12,000'.
'       Converted '12 425,00' to 12425.
'       Converted '12,425.00' to 12425.
'       '631,900' is out of range of the Int32 type.
'       Unable to convert '631,900'.
'       Converted '631,900' to 631900.

注解

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. 它必须是枚举中的位标志的组合 NumberStylesIt must be a combination of bit flags from the NumberStyles enumeration. 根据的值 styles 参数可能包括以下元素:Depending on the value of style, the s parameter may include the following elements:

ws[$]表明[数字,] 位数 [.fractional_digist] [e [sign] exponential_digits] [ws][ws][$][sign][digits,]digits[.fractional_digist][e[sign]exponential_digits][ws]

或者,如果 style 包括 AllowHexSpecifierOr, if style includes AllowHexSpecifier:

[ws] hexdigits [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.AllowTrailingWhiteWhite space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.
$ 区域性特定的货币符号。A culture-specific currency symbol. 其在字符串中的位置由 NumberFormatInfo.CurrencyPositivePattern NumberFormatInfo 参数方法返回的对象的属性定义 GetFormat providerIts position in the string is defined by the NumberFormatInfo.CurrencyPositivePattern property of the NumberFormatInfo object returned by the GetFormat method of the provider parameter. s如果包含标志,则货币符号可以出现在中 style NumberStyles.AllowCurrencySymbolThe 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 or at the end of s if style includes the NumberStyles.AllowTrailingSign flag. 如果包含标志,则可以在中使用括号 s 来表示负值 style NumberStyles.AllowParenthesesParentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
位数digits

fractional_digitsfractional_digits

exponential_digitsexponential_digits
介于0到9之间的一系列数字。A sequence of digits from 0 through 9. 对于 fractional_digits ,只有数字0有效。For fractional_digits , only the digit 0 is valid.
,, 区域性特定的千位分隔符。A culture-specific thousands separator symbol. 如果包含标志,则指定的区域性的千位分隔符 provider 可以出现在中 s style NumberStyles.AllowThousandsThe thousands separator of the culture specified by provider can appear in s if style includes the NumberStyles.AllowThousands flag.
.. 区域性特定的小数点符号。A culture-specific decimal point symbol. 如果包含标志,则指定的区域性的小数点符号 provider 可以出现在中 s style NumberStyles.AllowDecimalPointThe decimal point symbol of the culture specified by provider can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.

只有数字0才能作为小数位出现,以便分析操作成功;如果 fractional_digits 包含任何其他数字, OverflowException 则会引发。Only the digit 0 can appear as a fractional digit for the parse operation to succeed; if fractional_digits includes any other digit, an OverflowException is thrown.
ee "E" 或 "E" 字符,指示值以指数表示法表示。The 'e' or 'E' character, which indicates that the value is represented in exponential notation. s如果包含标志,则参数可以表示指数表示法中的数字 style NumberStyles.AllowExponentThe s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
hexdigitshexdigits 从0到 f 的十六进制数字序列,或者从0到 F。A sequence of hexadecimal digits from 0 through f, or 0 through F.

备注

s无论参数的值如何,分析操作都将忽略中任何终止的 NUL (U + 0000) 字符 styleAny terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

仅包含十进制数字的字符串 (与 NumberStyles.None 样式) 总是在该类型的范围内分析成功 Int32A string with decimal digits only (which corresponds to the NumberStyles.None style) always parses successfully if it is in the range of the Int32 type. 大多数其余 NumberStyles 成员控件元素在此输入字符串中可能已存在但不是必需的。Most of the remaining NumberStyles members control elements that may be but are not required to be present in this input string. 下表指示各个成员如何 NumberStyles 影响可能出现在中的元素 sThe following table indicates how individual NumberStyles members affect the elements that may be present in s.

非复合 NumberStyles 值Non-composite NumberStyles values 除数字外允许在 s 中使用的元素Elements permitted in s in addition to digits
NumberStyles.None 仅十进制数字。Decimal digits only.
NumberStyles.AllowDecimalPoint 小数点 ( The decimal point ( . ) 和 小数位数 元素。) and fractional-digits elements. 但是, 小数位数 必须仅包含一个或多个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. 如果 s 表示指数表示法中的数字,则该数字必须表示数据类型范围内的一个整数,该数据类型的范围内 Int32 没有非零的小数部分。If s represents a number in exponential notation, it must represent an integer within the range of the Int32 data type without a non-zero, fractional component.
NumberStyles.AllowLeadingWhite 开头的 ws 元素 sThe ws element at the beginning of s.
NumberStyles.AllowTrailingWhite 末尾处的 ws 元素 sThe ws element at the end of s.
NumberStyles.AllowLeadingSign 正负号可以出现在 数字 之前。A positive sign can appear before digits.
NumberStyles.AllowTrailingSign 正负号可以出现在 数字 之后。A positive sign can appear after digits.
NumberStyles.AllowParentheses 用括号括起数值的 符号 元素。The sign element in the form of parentheses enclosing the numeric value.
NumberStyles.AllowThousands 千位分隔符 ( ) 元素。The thousands separator ( , ) element.
NumberStyles.AllowCurrencySymbol $ 元素。The $ element.

如果 NumberStyles.AllowHexSpecifier 使用标志,则 s 必须是不带前缀的十六进制值。If the NumberStyles.AllowHexSpecifier flag is used, s must be a hexadecimal value without a prefix. 例如,"C9AF3" 分析成功,但 "0xC9AF3" 不能。For example, "C9AF3" parses successfully, but "0xC9AF3" does not. 中可以存在的唯一其他标志 styleNumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhiteThe 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 实现,如 NumberFormatInfoCultureInfo 对象。The provider parameter is an IFormatProvider implementation, such as a NumberFormatInfo or CultureInfo object. provider参数提供用于分析的特定于区域性的信息。The provider parameter supplies culture-specific information used in parsing. 如果 providernull ,则 NumberFormatInfo 使用当前区域性的对象。If provider is null, the NumberFormatInfo object for the current culture is used.

另请参阅

适用于

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

将指定样式和区域性特定格式的数字的范围表示形式转换为其等效的 32 位带符号整数。Converts the span representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent.

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

参数

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. 要指定的一个典型值为 IntegerA typical value to specify is Integer.

provider
IFormatProvider

一个对象,用于提供有关 s 格式的区域性特定信息。An object that supplies culture-specific information about the format of s.

返回

Int32

s 中指定的数字等效的 32 位带符号整数。A 32-bit signed integer equivalent to the number specified in s.

适用于

Parse(String, NumberStyles)

将指定样式的数字的字符串表示形式转换为它的等效 32 位有符号整数。Converts the string representation of a number in a specified style to its 32-bit signed integer equivalent.

public:
 static int Parse(System::String ^ s, System::Globalization::NumberStyles style);
public static int Parse (string s, System.Globalization.NumberStyles style);
static member Parse : string * System.Globalization.NumberStyles -> int
Public Shared Function Parse (s As String, style As NumberStyles) As Integer

参数

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. 要指定的一个典型值为 IntegerA typical value to specify is Integer.

返回

Int32

s 中指定的数字等效的 32 位带符号整数。A 32-bit signed integer equivalent to the number specified in s.

例外

snulls is null.

style 不是 NumberStyles 值。style is not a NumberStyles value.

- 或 --or- style 不是 AllowHexSpecifierHexNumber 值的组合。style is not a combination of AllowHexSpecifier and HexNumber values.

s 的格式不符合 styles 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.

示例

下面的示例使用 Int32.Parse(String, NumberStyles) 方法分析多个值的字符串表示形式 Int32The following example uses the Int32.Parse(String, NumberStyles) method to parse the string representations of several Int32 values. 该示例的当前区域性为 en-us。The current culture for the example is en-US.

using namespace System;
using namespace System::Globalization;

public ref class ParseInt32
{
public:
   static void Main()
   {
      Convert("104.0", NumberStyles::AllowDecimalPoint);
      Convert("104.9", NumberStyles::AllowDecimalPoint);
      Convert(" $17,198,064.42", NumberStyles::AllowCurrencySymbol |
                                 NumberStyles::Number);
      Convert("103E06", NumberStyles::AllowExponent);
      Convert("-1,345,791", NumberStyles::AllowThousands);
      Convert("(1,345,791)", NumberStyles::AllowThousands |
                             NumberStyles::AllowParentheses);
   }

private:
   static void Convert(String^ value, NumberStyles style)
   {
      try
      {
         int number = Int32::Parse(value, style);
         Console::WriteLine("Converted '{0}' to {1}.", value, number);
      }
      catch (FormatException^)
      {
         Console::WriteLine("Unable to convert '{0}'.", value);
      }
      catch (OverflowException^)
      {
         Console::WriteLine("'{0}' is out of range of the Int32 type.", value);
      }
   }
};

int main()
{
    ParseInt32::Main();
}
// The example displays the following output to the console:
//       Converted '104.0' to 104.
//       '104.9' is out of range of the Int32 type.
//       ' $17,198,064.42' is out of range of the Int32 type.
//       Converted '103E06' to 103000000.
//       Unable to convert '-1,345,791'.
//       Converted '(1,345,791)' to -1345791.
using System;
using System.Globalization;

public class ParseInt32
{
   public static void Main()
   {
      Convert("104.0", NumberStyles.AllowDecimalPoint);
      Convert("104.9", NumberStyles.AllowDecimalPoint);
      Convert(" $17,198,064.42", NumberStyles.AllowCurrencySymbol |
                                 NumberStyles.Number);
      Convert("103E06", NumberStyles.AllowExponent);
      Convert("-1,345,791", NumberStyles.AllowThousands);
      Convert("(1,345,791)", NumberStyles.AllowThousands |
                             NumberStyles.AllowParentheses);
   }

   private static void Convert(string value, NumberStyles style)
   {
      try
      {
         int number = Int32.Parse(value, style);
         Console.WriteLine("Converted '{0}' to {1}.", value, number);
      }
      catch (FormatException)
      {
         Console.WriteLine("Unable to convert '{0}'.", value);
      }
      catch (OverflowException)
      {
         Console.WriteLine("'{0}' is out of range of the Int32 type.", value);
      }
   }
}
// The example displays the following output to the console:
//       Converted '104.0' to 104.
//       '104.9' is out of range of the Int32 type.
//       ' $17,198,064.42' is out of range of the Int32 type.
//       Converted '103E06' to 103000000.
//       Unable to convert '-1,345,791'.
//       Converted '(1,345,791)' to -1345791.
Imports System.Globalization

Module ParseInt32
   Public Sub Main()
      Convert("104.0", NumberStyles.AllowDecimalPoint)    
      Convert("104.9", NumberStyles.AllowDecimalPoint)
      Convert(" $17,198,064.42", NumberStyles.AllowCurrencySymbol Or _
                                 NumberStyles.Number)
      Convert("103E06", NumberStyles.AllowExponent)  
      Convert("-1,345,791", NumberStyles.AllowThousands)
      Convert("(1,345,791)", NumberStyles.AllowThousands Or _
                             NumberStyles.AllowParentheses)
   End Sub
   
   Private Sub Convert(value As String, style As NumberStyles)
      Try
         Dim number As Integer = Int32.Parse(value, style)
         Console.WriteLine("Converted '{0}' to {1}.", value, number)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", value)
      Catch e As OverflowException
         Console.WriteLine("'{0}' is out of range of the Int32 type.", value)   
      End Try
   End Sub
End Module
' The example displays the following output to the console:
'       Converted '104.0' to 104.
'       '104.9' is out of range of the Int32 type.
'       ' $17,198,064.42' is out of range of the Int32 type.
'       Converted '103E06' to 103000000.
'       Unable to convert '-1,345,791'.
'       Converted '(1,345,791)' to -1345791.

注解

style参数定义 (如空格、正号或负号符号或千位分隔符符号) 的样式元素,以便 s 分析操作成功的参数。The style parameter defines the style elements (such as white space, the positive or negative sign symbol, or the thousands separator symbol) that are allowed in the s parameter for the parse operation to succeed. 它必须是枚举中的位标志的组合 NumberStylesIt must be a combination of bit flags from the NumberStyles enumeration. 根据的值 styles 参数可能包括以下元素:Depending on the value of style, the s parameter may include the following elements:

ws[$]表明[数字,] 位数 [.fractional_digits] [e [sign] exponential_digits] [ws][ws][$][sign][digits,]digits[.fractional_digits][e[sign]exponential_digits][ws]

或者,如果 style 包括 AllowHexSpecifierOr, if style includes AllowHexSpecifier:

[ws] hexdigits [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.AllowTrailingWhiteWhite space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.
$ 区域性特定的货币符号。A culture-specific currency symbol. 其在字符串中的位置由 NumberFormatInfo.CurrencyNegativePattern NumberFormatInfo.CurrencyPositivePattern 当前区域性的和属性定义。Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the current culture. s如果包含标志,则当前区域性的货币符号可以出现在中 style NumberStyles.AllowCurrencySymbolThe 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.AllowTrailingSignThe 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.AllowParenthesesParentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
位数digits

fractional_digitsfractional_digits

exponential_digitsexponential_digits
介于0到9之间的一系列数字。A sequence of digits from 0 through 9. 对于 fractional_digits ,只有数字0有效。For fractional_digits , only the digit 0 is valid.
,, 区域性特定的千位分隔符。A culture-specific thousands separator symbol. s如果包含标志,则当前区域性的千位分隔符可以出现在中 style NumberStyles.AllowThousandsThe current culture's thousands separator can appear in s if style includes the NumberStyles.AllowThousands flag.
.. 区域性特定的小数点符号。A culture-specific decimal point symbol. s如果包含标志,则当前区域性的小数点符号可以出现在中 style NumberStyles.AllowDecimalPointThe current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag. 只有数字0才能作为小数位出现,以便分析操作成功;如果 fractional_digits 包含任何其他数字, OverflowException 则会引发。Only the digit 0 can appear as a fractional digit for the parse operation to succeed; if fractional_digits includes any other digit, an OverflowException is thrown.
ee "E" 或 "E" 字符,指示值以指数表示法表示。The 'e' or 'E' character, which indicates that the value is represented in exponential notation. s如果包含标志,则参数可以表示指数表示法中的数字 style NumberStyles.AllowExponentThe s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
hexdigitshexdigits 从0到 f 的十六进制数字序列,或者从0到 F。A sequence of hexadecimal digits from 0 through f, or 0 through F.

备注

s无论参数的值如何,分析操作都将忽略中任何终止的 NUL (U + 0000) 字符 styleAny terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

只包含数字的字符串 (与样式相对应 NumberStyles.None) 始终在类型范围内分析成功 Int32A string with digits only (which corresponds to the NumberStyles.None style) always parses successfull if it is in the range of the Int32 type. 大多数其余 NumberStyles 成员控件元素在输入字符串中可能存在但不是必需的。Most of the remaining NumberStyles members control elements that may be but are not required to be present in the input string. 下表指示各个成员如何 NumberStyles 影响可能出现在中的元素 sThe following table indicates how individual NumberStyles members affect the elements that may be present in s.

NumberStyles 值NumberStyles value 除数字外允许在 s 中使用的元素Elements permitted in s in addition to digits
None 仅限 数字 元素。The digits element only.
AllowDecimalPoint 小数点 ( The decimal point ( . ) 和 小数位数 元素。) and fractional-digits elements.
AllowExponent s参数还可以使用指数表示法。The s parameter can also use exponential notation.
AllowLeadingWhite 开头的 ws 元素 sThe ws element at the beginning of s.
AllowTrailingWhite 末尾处的 ws 元素 sThe ws element at the end of s.
AllowLeadingSign 开头的 sign 元素 sThe sign element at the beginning of s.
AllowTrailingSign 末尾的 sign 元素 sThe sign element at the end of s.
AllowParentheses 用括号括起数值的 符号 元素。The sign element in the form of parentheses enclosing the numeric value.
AllowThousands 千位分隔符 ( ) 元素。The thousands separator ( , ) element.
AllowCurrencySymbol $ 元素。The $ element.
Currency 全部。All. s参数不能表示十六进制数或以指数表示法表示的数字。The s parameter cannot represent a hexadecimal number or a number in exponential notation.
Float 在开头或结尾处的 ws 元素,在 s 的开头处进行 签名s 而小数点 ( The ws element at the beginning or end of s, sign at the beginning of s, and the decimal point ( . ) 符号。) symbol. s参数还可以使用指数表示法。The s parameter can also use exponential notation.
Number ws (、 sign ) 和小数点 ( , 的、千位分隔符 The ws, sign, thousands separator ( , ), and decimal point ( . ) 元素。) elements.
Any 除之外的所有样式都 s 不能表示十六进制数。All styles, except s cannot represent a hexadecimal number.

如果 NumberStyles.AllowHexSpecifier 使用标志,则 s 必须是不带前缀的十六进制值。If the NumberStyles.AllowHexSpecifier flag is used, s must be a hexadecimal value without a prefix. 例如,"C9AF3" 分析成功,但 "0xC9AF3" 不能。For example, "C9AF3" parses successfully, but "0xC9AF3" does not. 可以与参数组合在一起的其他标志 sNumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhiteThe only other flags that can be combined with the s parameter it are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. 枚举 (NumberStyles 包含复合数字样式, NumberStyles.HexNumber 其中包含两个空格标志。 ) (The NumberStyles enumeration includes 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. 若要指定其格式设置信息用于分析操作的区域性,请调用 Int32.Parse(String, NumberStyles, IFormatProvider) 重载。To specify the culture whose formatting information is used for the parse operation, call the Int32.Parse(String, NumberStyles, IFormatProvider) overload.

另请参阅

适用于

Parse(String)

将数字的字符串表示形式转换为它的等效 32 位有符号整数。Converts the string representation of a number to its 32-bit signed integer equivalent.

public:
 static int Parse(System::String ^ s);
public static int Parse (string s);
static member Parse : string -> int
Public Shared Function Parse (s As String) As Integer

参数

s
String

包含要转换的数字的字符串。A string containing a number to convert.

返回

Int32

s 中包含的数字等效的 32 位有符号整数。A 32-bit signed integer equivalent to the number contained in s.

例外

snulls is null.

s 的格式不正确。s is not in the correct format.

s 表示一个小于 MinValue 或大于 MaxValue 的数字。s represents a number less than MinValue or greater than MaxValue.

示例

下面的示例演示如何使用方法将字符串值转换为32位带符号整数值 Int32.Parse(String)The following example demonstrates how to convert a string value into a 32-bit signed integer value using the Int32.Parse(String) method. 然后,将生成的整数值显示到控制台。The resulting integer value is then displayed to the console.

using namespace System;

void main()
{
   array<String^>^ values = { "+13230", "-0", "1,390,146", "$190,235,421,127",
                              "0xFA1B", "163042", "-10", "007", "2147483647", 
                              "2147483648", "16e07", "134985.0", "-12034",
                              "-2147483648", "-2147483649" };
   for each (String^ value in values)
   {
      try {
         Int32 number = Int32::Parse(value); 
         Console::WriteLine("{0} --> {1}", value, number);
      }
      catch (FormatException^ e) {
         Console::WriteLine("{0}: Bad Format", value);
      }   
      catch (OverflowException^ e) {
         Console::WriteLine("{0}: Overflow", value);   
      }  
   }
}
// The example displays the following output:
//       +13230 --> 13230
//       -0 --> 0
//       1,390,146: Bad Format
//       $190,235,421,127: Bad Format
//       0xFA1B: Bad Format
//       163042 --> 163042
//       -10 --> -10
//       007 --> 7
//       2147483647 --> 2147483647
//       2147483648: Overflow
//       16e07: Bad Format
//       134985.0: Bad Format
//       -12034 --> -12034
//       -2147483648 --> -2147483648
//       -2147483649: Overflow
using System;

public class Example
{
   public static void Main()
   {
      string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127",
                          "0xFA1B", "163042", "-10", "007", "2147483647",
                          "2147483648", "16e07", "134985.0", "-12034",
                          "-2147483648", "-2147483649" };
      foreach (string value in values)
      {
         try {
            int number = Int32.Parse(value);
            Console.WriteLine("{0} --> {1}", value, number);
         }
         catch (FormatException) {
            Console.WriteLine("{0}: Bad Format", value);
         }
         catch (OverflowException) {
            Console.WriteLine("{0}: Overflow", value);
         }
      }
   }
}
// The example displays the following output:
//       +13230 --> 13230
//       -0 --> 0
//       1,390,146: Bad Format
//       $190,235,421,127: Bad Format
//       0xFA1B: Bad Format
//       163042 --> 163042
//       -10 --> -10
//       007 --> 7
//       2147483647 --> 2147483647
//       2147483648: Overflow
//       16e07: Bad Format
//       134985.0: Bad Format
//       -12034 --> -12034
//       -2147483648 --> -2147483648
//       -2147483649: Overflow
Module Example
   Public Sub Main()
      Dim values() As String = { "+13230", "-0", "1,390,146", "$190,235,421,127",
                                 "0xFA1B", "163042", "-10", "007", "2147483647", 
                                 "2147483648", "16e07", "134985.0", "-12034",
                                 "-2147483648", "-2147483649"  }
      For Each value As String In values
         Try
            Dim number As Integer = Int32.Parse(value) 
            Console.WriteLine("{0} --> {1}", value, number)
         Catch e As FormatException
            Console.WriteLine("{0}: Bad Format", value)
         Catch e As OverflowException
            Console.WriteLine("{0}: Overflow", value)   
         End Try  
      Next
   End Sub
End Module
' The example displays the following output:
'       +13230 --> 13230
'       -0 --> 0
'       1,390,146: Bad Format
'       $190,235,421,127: Bad Format
'       0xFA1B: Bad Format
'       163042 --> 163042
'       -10 --> -10
'       007 --> 7
'       2147483647 --> 2147483647
'       2147483648: Overflow
'       16e07: Bad Format
'       134985.0: Bad Format
'       -12034 --> -12034
'       -2147483648 --> -2147483648
'       -2147483649: Overflow

注解

s参数包含以下格式的编号:The s parameter contains a number of the form:

ws[sign] 位数 [ws][ws][sign]digits[ws]

方括号 ( [和] ) 中的项是可选的。Items in square brackets ([ and ]) are optional. 下表对每个元素进行了描述。The following table describes each element.

元素Element 说明Description
wsws 可选空白。Optional white space.
签名sign 一个可选的符号。An optional sign.
位数digits 介于0到9之间的一系列数字。A sequence of digits ranging from 0 to 9.

s使用样式对参数进行解释 NumberStyles.IntegerThe s parameter is interpreted using the NumberStyles.Integer style. 除了十进制数字外,只允许使用前导和尾随空格以及前导符号。In addition to decimal digits, only leading and trailing spaces together with a leading sign are allowed. 若要显式定义可出现在中的样式元素 s ,请使用 Int32.Parse(String, NumberStyles)Int32.Parse(String, NumberStyles, IFormatProvider) 方法。To explicitly define the style elements that can be present in s, use either the Int32.Parse(String, NumberStyles) or the Int32.Parse(String, NumberStyles, IFormatProvider) method.

s使用 NumberFormatInfo 为当前系统区域性初始化的对象中的格式设置信息分析参数。The s parameter is parsed using the formatting information in a NumberFormatInfo object initialized for the current system culture. 有关详细信息,请参阅 CurrentInfoFor more information, see CurrentInfo. 若要使用其他某个区域性的格式设置信息分析字符串,请使用 Int32.Parse(String, NumberStyles, IFormatProvider) 方法。To parse a string using the formatting information of some other culture, use the Int32.Parse(String, NumberStyles, IFormatProvider) method.

另请参阅

适用于

Parse(String, IFormatProvider)

将指定的区域性特定格式的数字的字符串表示形式转换为它的等效 32 位有符号整数。Converts the string representation of a number in a specified culture-specific format to its 32-bit signed integer equivalent.

public:
 static int Parse(System::String ^ s, IFormatProvider ^ provider);
public static int Parse (string s, IFormatProvider provider);
public static int Parse (string s, IFormatProvider? provider);
static member Parse : string * IFormatProvider -> int
Public Shared Function Parse (s As String, provider As IFormatProvider) As Integer

参数

s
String

包含要转换的数字的字符串。A string containing a number to convert.

provider
IFormatProvider

一个对象,提供有关 s 的区域性特定格式设置信息。An object that supplies culture-specific formatting information about s.

返回

Int32

s 中指定的数字等效的 32 位带符号整数。A 32-bit signed integer equivalent to the number specified in s.

例外

snulls is null.

s 的格式不正确。s is not of the correct format.

s 表示一个小于 MinValue 或大于 MaxValue 的数字。s represents a number less than MinValue or greater than MaxValue.

示例

下面的示例是 Web 窗体的按钮单击事件处理程序。The following example is the button click event handler of a Web form. 它使用属性返回的数组 HttpRequest.UserLanguages 来确定用户的区域设置。It uses the array returned by the HttpRequest.UserLanguages property to determine the user's locale. 然后,它将实例化 CultureInfo 对应于该区域设置的对象。It then instantiates a CultureInfo object that corresponds to that locale. 然后,将 NumberFormatInfo 属于该对象的对象 CultureInfo 传递给 Parse(String, IFormatProvider) 方法,以将用户的输入转换为 Int32 值。The NumberFormatInfo object that belongs to that CultureInfo object is then passed to the Parse(String, IFormatProvider) method to convert the user's input to an Int32 value.

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

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

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

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

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

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

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

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

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

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

注解

此方法的重载 Parse(String, IFormatProvider) 通常用于将可以多种方式设置格式的文本转换为 Int32 值。This overload of the Parse(String, IFormatProvider) method is typically used to convert text that can be formatted in a variety of ways to an Int32 value. 例如,它可用于将用户输入的文本转换为一个数字值。For example, it can be used to convert the text entered by a user into an HTML text box to a numeric value.

s参数包含以下格式的编号:The s parameter contains a number of the form:

ws[sign] 位数 [ws][ws][sign]digits[ws]

方括号 ( [和] ) 中的项是可选的。Items in square brackets ([ and ]) are optional. 下表对每个元素进行了描述。The following table describes each element.

元素Element 说明Description
wsws 可选空白。Optional white space.
signsign 一个可选的符号。An optional sign.
位数digits 介于0到9之间的一系列数字。A sequence of digits ranging from 0 to 9.

s使用样式对参数进行解释 NumberStyles.IntegerThe s parameter is interpreted using the NumberStyles.Integer style. 除了十进制数字外,只允许使用前导和尾随空格以及前导符号。In addition to decimal digits, only leading and trailing spaces together with a leading sign are allowed. 若要显式定义可出现在中的样式元素 s ,请使用 Int32.Parse(String, NumberStyles, IFormatProvider) 方法。To explicitly define the style elements that can be present in s, use the Int32.Parse(String, NumberStyles, IFormatProvider) method.

provider参数是一个 IFormatProvider 实现,如 NumberFormatInfoCultureInfo 对象。The provider parameter is an IFormatProvider implementation, such as a NumberFormatInfo or CultureInfo object. provider参数提供有关的格式的区域性特定信息 sThe provider parameter supplies culture-specific information about the format of s. 如果 providernull ,则 NumberFormatInfo 使用当前区域性的对象。If provider is null, the NumberFormatInfo object for the current culture is used.

另请参阅

适用于