SByte.Parse 方法

定义

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

重载

Parse(String, NumberStyles, IFormatProvider)

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

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

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

Parse(String, NumberStyles)

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

Parse(String)

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

Parse(String, IFormatProvider)

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

Parse(String, NumberStyles, IFormatProvider)

重要

此 API 不符合 CLS。

符合 CLS 的替代方案
System.Int16.Parse(String, NumberStyles, IFormatProvider)

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

public:
 static System::SByte Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
[System.CLSCompliant(false)]
public static sbyte Parse (string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static sbyte Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static sbyte Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> sbyte
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> sbyte
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As SByte

参数

s
String

包含要转换的数字的字符串。A string that contains the number to convert. 该字符串使用由 style 指定的样式来进行解释。The string is interpreted by using the style specified by style.

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.

provider
IFormatProvider

一个对象,提供有关 s 的区域性特定格式设置信息。An object that supplies culture-specific formatting information about s. 如果 providernull,则使用当前区域性。If provider is null, the thread current culture is used.

返回

SByte

s 参数中指定的数字等效的 8 位有符号字节值。An 8-bit signed byte value that is equivalent to the number specified in the s parameter.

属性

例外

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

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

snulls is null.

s 的格式不符合 styles is not in a format that is compliant with style.

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

- 或 --or- s 包含非零的小数位。s includes non-zero, fractional digits.

示例

下面的示例演示如何使用方法将 Parse(String, NumberStyles, IFormatProvider) 数字的各种字符串表示形式转换为有符号整数值。The following example illustrates the use of the Parse(String, NumberStyles, IFormatProvider) method to convert various string representations of numbers to signed integer values.

using System;
using System.Globalization;

public class SByteConversion
{
   NumberFormatInfo provider = NumberFormatInfo.CurrentInfo;

   public static void Main()
   {
      string stringValue;
      NumberStyles style;

      stringValue = "   123   ";
      style = NumberStyles.None;     
      CallParseOperation(stringValue, style);
      
      stringValue = "000,000,123";
      style = NumberStyles.Integer | NumberStyles.AllowThousands;
      CallParseOperation(stringValue, style);
      
      stringValue = "-100";
      style = NumberStyles.AllowLeadingSign;
      CallParseOperation(stringValue, style);
      
      stringValue = "100-";
      style = NumberStyles.AllowLeadingSign;
      CallParseOperation(stringValue, style);
      
      stringValue = "100-";
      style = NumberStyles.AllowTrailingSign;
      CallParseOperation(stringValue, style);
      
      stringValue = "$100";
      style = NumberStyles.AllowCurrencySymbol;
      CallParseOperation(stringValue, style);
      
      style = NumberStyles.Integer;
      CallParseOperation(stringValue, style);
      
      style = NumberStyles.AllowDecimalPoint;
      CallParseOperation("100.0", style);
      
      stringValue = "1e02";
      style = NumberStyles.AllowExponent;
      CallParseOperation(stringValue, style);
      
      stringValue = "(100)";
      style = NumberStyles.AllowParentheses;
      CallParseOperation(stringValue, style);
   }
   
   private static void CallParseOperation(string stringValue, 
                                          NumberStyles style)
   {                                          
      sbyte number;
      
      if (stringValue == null)
         Console.WriteLine("Cannot parse a null string...");
         
      try
      {
         number = sbyte.Parse(stringValue, style);
         Console.WriteLine("SByte.Parse('{0}', {1})) = {2}", 
                           stringValue, style, number);   
      }
      catch (FormatException)
      {
         Console.WriteLine("'{0}' and {1} throw a FormatException", 
                           stringValue, style);   
      }      
      catch (OverflowException)
      {
         Console.WriteLine("'{0}' is outside the range of a signed byte",
                           stringValue);
      }
   }
}
// The example displays the following information to the console:
//       '   123   ' and None throw a FormatException
//       SByte.Parse('000,000,123', Integer, AllowThousands)) = 123
//       SByte.Parse('-100', AllowLeadingSign)) = -100
//       '100-' and AllowLeadingSign throw a FormatException
//       SByte.Parse('100-', AllowTrailingSign)) = -100
//       SByte.Parse('$100', AllowCurrencySymbol)) = 100
//       '$100' and Integer throw a FormatException
//       SByte.Parse('100.0', AllowDecimalPoint)) = 100
//       SByte.Parse('1e02', AllowExponent)) = 100
//       SByte.Parse('(100)', AllowParentheses)) = -100
Imports System.Globalization

Module modMain
   Public Sub Main()
      Dim byteString As String 
      
      byteString = " 123"
      ParseString(byteString, NumberStyles.None)
      ParseString(byteString, NumberStyles.Integer)
      
      byteString = "3A"
      ParseString(byteString, NumberStyles.AllowHexSpecifier) 
      
      byteString = "21"
      ParseString(byteString, NumberStyles.Integer)
      ParseString(byteString, NumberStyles.AllowHexSpecifier)
      
      byteString = "-22"
      ParseString(byteString, NumberStyles.Integer)
      ParseString(byteString, NumberStyles.AllowParentheses)
      
      byteString = "(45)"
      ParseString(byteString, NumberStyles.AllowParentheses)
     
      byteString = "000,000,056"
      ParseString(byteString, NumberStyles.Integer)
      ParseString(byteString, NumberStyles.Integer Or NumberStyles.AllowThousands)
   End Sub
   
   Private Sub ParseString(value As String, style As NumberStyles)
      Dim number As SByte
      
      If value Is Nothing Then Console.WriteLine("Cannot parse a null string...") 
      
      Try
         number = SByte.Parse(value, style, NumberFormatInfo.CurrentInfo)
         Console.WriteLine("SByte.Parse('{0}', {1}) = {2}", value, style, number)   
      Catch e As FormatException
         Console.WriteLine("'{0}' and {1} throw a FormatException", value, style)   
      Catch e As OverflowException
         Console.WriteLine("'{0}' is outside the range of a signed byte",
                           value)
      End Try     
   End Sub
End Module
' The example displays the following information to the console:
'       ' 123' and None throw a FormatException
'       SByte.Parse(" 123", Integer)) = 123
'       SByte.Parse("3A", AllowHexSpecifier)) = 58
'       SByte.Parse("21", Integer)) = 21
'       SByte.Parse("21", AllowHexSpecifier)) = 33
'       SByte.Parse("-22", Integer)) = -22
'       '-22' and AllowParentheses throw a FormatException
'       SByte.Parse("(45)", AllowParentheses)) = -45
'       '000,000,056' and Integer throw a FormatException
'       SByte.Parse("000,000,056", Integer, AllowThousands)) = 56

注解

style参数定义在参数中允许的样式元素 (如空格或正号或负号符号) ,以便 s 分析操作成功。The style parameter defines the style elements (such as white space or the positive or negative sign 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][ $ ] [sign]位数[。fractional_digits] [E [sign]exponential_digits] [ws][ws][$][sign]digits[.fractional_digits][E[sign]exponential_digits][ws]

如果 style 包含 AllowHexSpecifier ,则 s 参数可能包括以下元素:If style includes AllowHexSpecifier, the s parameter may include the following elements:

[ws]hexdigits[ws][ws]hexdigits[ws]

方括号 ([ and ]) 中的元素是可选的。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.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 当前区域性的属性定义。Its position in the string is defined by the NumberFormatInfo.CurrencyPositivePattern property 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 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 介于0到9之间的一系列数字。A sequence of digits from 0 through 9.
.. 区域性特定的小数点符号。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.
fractional_digitsfractional_digits 如果包含标志,则为数字0-9 的一个或多个匹配项 style NumberStyles.AllowExponent ,如果未出现,则为数字0的一个或多个匹配项。One or more occurrences of the digit 0-9 if style includes the NumberStyles.AllowExponent flag, or one or more occurrences of the digit 0 if it does not. s仅当包含标志时,小数位才能出现在中 style NumberStyles.AllowDecimalPointFractional digits can appear in s only if style includes the NumberStyles.AllowDecimalPoint flag.
EE "E" 或 "E" 字符,指示以指数 (科学) 记数法表示的值。The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation. s如果包含标志,则参数可以表示指数表示法中的数字 style NumberStyles.AllowExponentThe s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
exponential_digitsexponential_digits 介于0到9之间的一系列数字。A sequence of digits from 0 through 9. 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 样式) 总是成功分析的字符串。A string with decimal digits only (which corresponds to the NumberStyles.None style) always parses successfully. 大多数其余 NumberStyles 成员控件在此输入字符串中可能存在但并不需要存在的元素。Most of the remaining NumberStyles members control elements that may be present, 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.

非复合 NumberStylesNon-composite NumberStyles values 中允许的元素 s 以及数字Elements permitted in s in addition to digits
NumberStyles.None 仅十进制数字。Decimal digits only.
NumberStyles.AllowDecimalPoint 小数点 () 和 fractional_digits 元素。The decimal point (.) and fractional_digits elements. 但是,如果样式不包含 NumberStyles.AllowExponent 标志,则 fractional_digits 必须仅包含一个或多个0位数; 否则, OverflowException 将引发。However, if style does not include the NumberStyles.AllowExponent flag, fractional_digits must consist of only one or more 0 digits; otherwise, an OverflowException is thrown.
NumberStyles.AllowExponent "E" 或 "E" 字符(指示指数表示法)以及 exponential_digitsThe "e" or "E" character, which indicates exponential notation, along with exponential_digits.
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 before digits.
NumberStyles.AllowTrailingSign 后的正负号。A positive sign after digits.
NumberStyles.AllowParentheses 用于指示负值的 位数 前后的括号。Parentheses before and after digits to indicate a negative value.
NumberStyles.AllowThousands 组分隔符 () 元素。The group separator (,) element. 尽管组分隔符可以出现在中 s ,但它前面必须仅有一个或多个0数字。Although the group separator can appear in s, it must be preceded by only one or more 0 digits.
NumberStyles.AllowCurrencySymbol 货币 ($) 元素。The currency ($) element.

如果 NumberStyles.AllowHexSpecifier 使用标志,则 s 必须是十六进制值。If the NumberStyles.AllowHexSpecifier flag is used, s must be a hexadecimal value. 有效的十六进制数字为0-9、a-f 和 A-f。Valid hexadecimal digits are 0-9, a-f, and A-F. 可以与之组合的其他标志只能是 NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhiteThe only other flags that can be combined with 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 参数是十六进制数的字符串表示形式,则它的前面不能有任何修饰 (例如 0x 或) ,它将 &h 其视为十六进制数。If the s parameter is the string representation of a hexadecimal number, it cannot be preceded by any decoration (such as 0x or &h) that differentiates it as a hexadecimal number. 这将导致分析操作引发异常。This causes the parse operation to throw an exception.

如果 s 表示十六进制数,则该 Parse(String, NumberStyles) 方法会将字节的高序位解释为符号位。If s represents a hexadecimal number, the Parse(String, NumberStyles) method interprets the high-order bit of the byte as a sign bit.

provider参数是一个 IFormatProvider 实现,其 GetFormat 方法返回一个 NumberFormatInfo 对象,该对象提供有关格式的区域性特定信息 sThe provider parameter is an IFormatProvider implementation whose GetFormat method returns a NumberFormatInfo object that provides culture-specific information about the format of s. 使用 provider 参数为分析操作提供自定义格式设置信息的方法有三种:There are three ways to use the provider parameter to supply custom formatting information to the parse operation:

如果 providernull ,则 NumberFormatInfo 使用当前区域性的对象。If provider is null, the NumberFormatInfo object for the current culture is used.

适用于

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

重要

此 API 不符合 CLS。

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

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

参数

s
ReadOnlySpan<Char>

一个范围,包含表示要转换的数字的字符。A span containing the characters representing the number to convert. 该范围使用由 style 指定的样式来进行解释。The span is interpreted by using the style specified by style.

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.

provider
IFormatProvider

一个对象,提供有关 s 的区域性特定格式设置信息。An object that supplies culture-specific formatting information about s. 如果 providernull,则使用当前区域性。If provider is null, the thread current culture is used.

返回

SByte

s 参数中指定的数字等效的 8 位有符号字节值。An 8-bit signed byte value that is equivalent to the number specified in the s parameter.

属性

适用于

Parse(String, NumberStyles)

重要

此 API 不符合 CLS。

符合 CLS 的替代方案
System.Int16.Parse(String)

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

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

参数

s
String

包含要转换的数字的字符串。A string that contains a number to convert. 该字符串使用由 style 指定的样式来进行解释。The string is interpreted using the style specified by style.

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.

返回

SByte

s 中指定的数字等效的 8 位有符号整数。An 8-bit signed integer that is equivalent to the number specified in s.

属性

例外

snulls is null.

s 的格式不符合 styles is not in a format that is 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 不是 NumberStyles 值。style is not a NumberStyles value.

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

示例

下面的示例通过方法分析值的字符串表示形式 SByte Parse(String, NumberStyles)The following example parses string representations of SByte values with the Parse(String, NumberStyles) method. 该示例的当前区域性为 en-us。The current culture for the example is en-US.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      NumberStyles style;
      sbyte number;

      // Parse value with no styles allowed.
      string[] values1 = { " 121 ", "121", "-121" };
      style = NumberStyles.None;
      Console.WriteLine("Styles: {0}", style.ToString());
      foreach (string value in values1)
      {
         try {
            number = SByte.Parse(value, style);
            Console.WriteLine("   Converted '{0}' to {1}.", value, number);
         }   
         catch (FormatException) {
            Console.WriteLine("   Unable to parse '{0}'.", value);
         }
      }
      Console.WriteLine();
            
      // Parse value with trailing sign.
      style = NumberStyles.Integer | NumberStyles.AllowTrailingSign;
      string[] values2 = { " 103+", " 103 +", "+103", "(103)", "   +103  " };
      Console.WriteLine("Styles: {0}", style.ToString());
      foreach (string value in values2)
      {
         try {
            number = SByte.Parse(value, style);
            Console.WriteLine("   Converted '{0}' to {1}.", value, number);
         }   
         catch (FormatException) {
            Console.WriteLine("   Unable to parse '{0}'.", value);
         }      
         catch (OverflowException) {
            Console.WriteLine("   '{0}' is out of range of the SByte type.", value);         
         }
      }      
      Console.WriteLine();
   }
}
// The example displays the following output:
//       Styles: None
//          Unable to parse ' 121 '.
//          Converted '121' to 121.
//          Unable to parse '-121'.
//       
//       Styles: Integer, AllowTrailingSign
//          Converted ' 103+' to 103.
//          Converted ' 103 +' to 103.
//          Converted '+103' to 103.
//          Unable to parse '(103)'.
//          Converted '   +103  ' to 103.
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim style As NumberStyles
      Dim number As SByte

      ' Parse value with no styles allowed.
      Dim values1() As String = { " 121 ", "121", "-121" }
      style = NumberStyles.None
      Console.WriteLine("Styles: {0}", style.ToString())
      For Each value As String In values1
         Try
            number = SByte.Parse(value, style)
            Console.WriteLine("   Converted '{0}' to {1}.", value, number)
         Catch e As FormatException
            Console.WriteLine("   Unable to parse '{0}'.", value)   
         End Try
      Next
      Console.WriteLine()
            
      ' Parse value with trailing sign.
      style = NumberStyles.Integer Or NumberStyles.AllowTrailingSign
      Dim values2() As String = { " 103+", " 103 +", "+103", "(103)", "   +103  " }
      Console.WriteLine("Styles: {0}", style.ToString())
      For Each value As String In values2
         Try
            number = SByte.Parse(value, style)
            Console.WriteLine("   Converted '{0}' to {1}.", value, number)
         Catch e As FormatException
            Console.WriteLine("   Unable to parse '{0}'.", value)   
         Catch e As OverflowException
            Console.WriteLine("   '{0}' is out of range of the SByte type.", value)         
         End Try
      Next      
      Console.WriteLine()
   End Sub
End Module
' The example displays the following output:
'       Styles: None
'          Unable to parse ' 121 '.
'          Converted '121' to 121.
'          Unable to parse '-121'.
'       
'       Styles: Integer, AllowTrailingSign
'          Converted ' 103+' to 103.
'          Converted ' 103 +' to 103.
'          Converted '+103' to 103.
'          Unable to parse '(103)'.
'          Converted '   +103  ' to 103.

注解

style参数定义在参数中允许的样式元素 (如空格或正号或负号符号) ,以便 s 分析操作成功。The style parameter defines the style elements (such as white space or the positive or negative sign 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][ $ ] [sign]位数[。fractional_digits] [E [sign]exponential_digits] [ws][ws][$][sign]digits[.fractional_digits][E[sign]exponential_digits][ws]

如果 style 包含 NumberStyles.AllowHexSpecifier ,则 s 参数可能包含以下元素:If style includes NumberStyles.AllowHexSpecifier, the s parameter may contain the following elements:

[ws]hexdigits[ws][ws]hexdigits[ws]

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

元素Element 说明Description
wsws 可选空白。Optional white space. 如果包含标志,则空格可以出现在的开头 s style NumberStyles.AllowLeadingWhites 如果 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 当前区域性的属性定义。Its position in the string is defined by the NumberFormatInfo.CurrencyPositivePattern property 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 介于0到9之间的一系列数字。A sequence of digits from 0 through 9.
.. 区域性特定的小数点符号。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.
fractional_digitsfractional_digits 如果包含标志,则为数字0-9 的一个或多个匹配项 style NumberStyles.AllowExponent ,如果未出现,则为数字0的一个或多个匹配项。One or more occurrences of the digit 0-9 if style includes the NumberStyles.AllowExponent flag, or one or more occurrences of the digit 0 if it does not. s仅当包含标志时,小数位才能出现在中 style NumberStyles.AllowDecimalPointFractional digits can appear in s only if style includes the NumberStyles.AllowDecimalPoint flag.
EE "E" 或 "E" 字符,指示以指数 (科学) 记数法表示的值。The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation. s如果包含标志,则参数可以表示指数表示法中的数字 style NumberStyles.AllowExponentThe s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
exponential_digitsexponential_digits 位数0-9 的一个或多个匹配项。One or more occurrences of the digit 0-9. 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 样式) 总是成功分析的字符串。A string with decimal digits only (which corresponds to the NumberStyles.None style) always parses successfully. 大多数剩余 NumberStyles 成员控件可能存在但不需要存在于输入字符串中的元素。Most of the remaining NumberStyles members control elements that may be present, 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 值Non-composite NumberStyles values 除数字外允许在 s 中使用的元素Elements permitted in s in addition to digits
NumberStyles.None 仅十进制数字。Decimal digits only.
NumberStyles.AllowDecimalPoint 小数点 () 和 fractional_digits 元素。The decimal point (.) and fractional_digits elements. 但是,如果不 style 包含 NumberStyles.AllowExponent 标志,则 fractional_digits 必须仅包含一个或多个0位数; 否则, OverflowException 将引发。However, if style does not include the NumberStyles.AllowExponent flag, fractional_digits must consist of only one or more 0 digits; otherwise, an OverflowException is thrown.
NumberStyles.AllowExponent "E" 或 "E" 字符(指示指数表示法)以及 exponential_digitsThe "e" or "E" character, which indicates exponential notation, along with exponential_digits.
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 before digits.
NumberStyles.AllowTrailingSign 后的正负号。A positive sign after digits.
NumberStyles.AllowParentheses 用括号括起数值的 符号 元素。The sign element in the form of parentheses enclosing the numeric value.
NumberStyles.AllowThousands 组分隔符 (,) 元素。The group separator (,) element. 尽管组分隔符可以出现在中 s ,但它前面必须仅有一个或多个0数字。Although the group separator can appear in s, it must be preceded by only one or more 0 digits.
NumberStyles.AllowCurrencySymbol 货币 ($) 元素。The currency ($) element.

如果 NumberStyles.AllowHexSpecifier 使用标志,则 s 必须是十六进制值。If the NumberStyles.AllowHexSpecifier flag is used, s must be a hexadecimal value. 有效的十六进制数字为0-9、a-f 和 A-f。Valid hexadecimal digits are 0-9, a-f, and A-F. 前缀(如 "0x")不受支持,导致分析操作失败。A prefix such as "0x" is not supported and causes the parse operation to fail. 可以组合的唯一其他标志 styleNumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhiteThe only other flags that can be combined included in style 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 参数是十六进制数的字符串表示形式,则它的前面不能有任何修饰 (例如 0x 或) ,它将 &h 其视为十六进制数。If the s parameter is the string representation of a hexadecimal number, it cannot be preceded by any decoration (such as 0x or &h) that differentiates it as a hexadecimal number. 这将导致分析操作引发异常。This causes the parse operation to throw an exception.

如果 s 表示十六进制数,则该 Parse(String, NumberStyles) 方法会将字节的高序位解释为符号位。If s represents a hexadecimal number, the Parse(String, NumberStyles) method interprets the high-order bit of the byte as a sign bit.

s通过使用为 NumberFormatInfo 当前系统区域性初始化的对象中的格式设置信息来分析参数。The s parameter is parsed by using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. 若要使用其他某个区域性的格式设置信息,请调用 Parse(String, NumberStyles, IFormatProvider) 重载。To use the formatting information of some other culture, call the Parse(String, NumberStyles, IFormatProvider) overload.

另请参阅

适用于

Parse(String)

重要

此 API 不符合 CLS。

符合 CLS 的替代方案
System.Int16.Parse(String)

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

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

参数

s
String

表示要转换的数字的字符串。A string that represents a number to convert. 该字符串使用 Integer 样式来进行解释。The string is interpreted using the Integer style.

返回

SByte

s 参数中包含的数字等效的 8 位有符号整数。An 8-bit signed integer that is equivalent to the number contained in the s parameter.

属性

例外

snulls is null.

s 不是由一个可选符号后跟一系列数字 (0-9) 组成的。s does not consist of an optional sign followed by a sequence of digits (zero through nine).

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

示例

下面的示例演示如何使用方法将字符串值转换为有符号字节值 ParseThe following example demonstrates how to convert a string value into a signed byte value using the Parse method. 然后,将生成的带符号字节值显示到控制台。The resulting signed byte value is then displayed to the console.

// Define an array of numeric strings.
string[] values = { "-16", "  -3", "+ 12", " +12 ", "  12  ",
                    "+120", "(103)", "192", "-160" };
                           
// Parse each string and display the result.
foreach (string value in values)
{
   try {
      Console.WriteLine("Converted '{0}' to the SByte value {1}.",
                        value, SByte.Parse(value));
   }
   catch (FormatException) {
      Console.WriteLine("'{0}' cannot be parsed successfully by SByte type.",
                        value);
   }                              
   catch (OverflowException) {
      Console.WriteLine("'{0}' is out of range of the SByte type.",
                        value);
   }                                                                        
}
// The example displays the following output:
//       Converted '-16' to the SByte value -16.
//       Converted '  -3' to the SByte value -3.
//       '+ 12' cannot be parsed successfully by SByte type.
//       Converted ' +12 ' to the SByte value 12.
//       Converted '  12  ' to the SByte value 12.
//       Converted '+120' to the SByte value 120.
//       '(103)' cannot be parsed successfully by SByte type.
//       '192' is out of range of the SByte type.
//       '-160' is out of range of the SByte type.
' Define an array of numeric strings.
Dim values() As String = { "-16", "  -3", "+ 12", " +12 ", "  12  ", _
                           "+120", "(103)", "192", "-160" }
                           
' Parse each string and display the result.
For Each value As String In values
   Try
      Console.WriteLine("Converted '{0}' to the SByte value {1}.", _
                        value, SByte.Parse(value))
   Catch e As FormatException
      Console.WriteLine("'{0}' cannot be parsed successfully by SByte type.", _
                        value)
   Catch e As OverflowException
      Console.WriteLine("'{0}' is out of range of the SByte type.", _
                        value)
   End Try                                                                        
Next        
' The example displays the following output:
'       Converted '-16' to the SByte value -16.
'       Converted '  -3' to the SByte value -3.
'       '+ 12' cannot be parsed successfully by SByte type.
'       Converted ' +12 ' to the SByte value 12.
'       Converted '  12  ' to the SByte value 12.
'       Converted '+120' to the SByte value 120.
'       '(103)' cannot be parsed successfully by SByte type.
'       '192' is out of range of the SByte type.
'       '-160' is out of range of the SByte type.

注解

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

[ws][sign]数字[ws][ws][sign]digits[ws]

方括号 ([ and ]) 中的元素是可选的。Elements 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 the byte value's decimal digits, only leading and trailing spaces with a leading positive or negative sign are allowed. 若要显式定义可出现在中的样式元素 s ,请使用 Parse(String, NumberStyles)Parse(String, NumberStyles, IFormatProvider) 方法。To explicitly define the style elements that can be present in s, use either the Parse(String, NumberStyles) or the Parse(String, NumberStyles, IFormatProvider) method.

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

另请参阅

适用于

Parse(String, IFormatProvider)

重要

此 API 不符合 CLS。

符合 CLS 的替代方案
System.Int16.Parse(String)

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

public:
 static System::SByte Parse(System::String ^ s, IFormatProvider ^ provider);
[System.CLSCompliant(false)]
public static sbyte Parse (string s, IFormatProvider provider);
public static sbyte Parse (string s, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static sbyte Parse (string s, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * IFormatProvider -> sbyte
static member Parse : string * IFormatProvider -> sbyte
Public Shared Function Parse (s As String, provider As IFormatProvider) As SByte

参数

s
String

表示要转换的数字的字符串。A string that represents a number to convert. 该字符串使用 Integer 样式来进行解释。The string is interpreted using the Integer style.

provider
IFormatProvider

一个对象,提供有关 s 的区域性特定格式设置信息。An object that supplies culture-specific formatting information about s. 如果 providernull,则使用当前区域性。If provider is null, the thread current culture is used.

返回

SByte

s 中指定的数字等效的 8 位有符号整数。An 8-bit signed integer that is equivalent to the number specified 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.

示例

下面的示例定义了一个自定义 NumberFormatInfo 对象,该对象定义颚化符 (~) 为负号。The following example defines a custom NumberFormatInfo object that defines the tilde (~) as the negative sign. 然后,它使用此自定义 NumberFormatInfo 对象以及 CultureInfo 表示固定区域性的对象来分析大量数值字符串。It then parses a number of numeric strings using this custom NumberFormatInfo object as well as a CultureInfo object that represents the invariant culture.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      NumberFormatInfo nf = new NumberFormatInfo();
      nf.NegativeSign = "~"; 
      
      string[] values = { "-103", "+12", "~16", "  1", "~255" };
      IFormatProvider[] providers = { nf, CultureInfo.InvariantCulture };
      
      foreach (IFormatProvider provider in providers)
      {
         Console.WriteLine("Conversions using {0}:", ((object) provider).GetType().Name);
         foreach (string value in values)
         {
            try {
               Console.WriteLine("   Converted '{0}' to {1}.", 
                                 value, SByte.Parse(value, provider));
            }                     
            catch (FormatException) {
               Console.WriteLine("   Unable to parse '{0}'.", value);   
            }
            catch (OverflowException) {
               Console.WriteLine("   '{0}' is out of range of the SByte type.", value);         
            }
         }
      }      
   }
}
// The example displays the following output:
//       Conversions using NumberFormatInfo:
//          Unable to parse '-103'.
//          Converted '+12' to 12.
//          Converted '~16' to -16.
//          Converted '  1' to 1.
//          '~255' is out of range of the SByte type.
//       Conversions using CultureInfo:
//          Converted '-103' to -103.
//          Converted '+12' to 12.
//          Unable to parse '~16'.
//          Converted '  1' to 1.
//          Unable to parse '~255'.
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim nf As New NumberFormatInfo()
      nf.NegativeSign = "~" 
      
      Dim values() As String = { "-103", "+12", "~16", "  1", "~255" }
      Dim providers() As IFormatProvider = { nf, CultureInfo.InvariantCulture }
      
      For Each provider As IFormatProvider In providers
         Console.WriteLine("Conversions using {0}:", CObj(provider).GetType().Name)
         For Each value As String In values
            Try
               Console.WriteLine("   Converted '{0}' to {1}.", _
                                 value, SByte.Parse(value, provider))
            Catch e As FormatException
               Console.WriteLine("   Unable to parse '{0}'.", value)   
            Catch e As OverflowException
               Console.WriteLine("   '{0}' is out of range of the SByte type.", value)         
            End Try
         Next
      Next      
   End Sub
End Module
' The example displays '
'       Conversions using NumberFormatInfo:
'          Unable to parse '-103'.
'          Converted '+12' to 12.
'          Converted '~16' to -16.
'          Converted '  1' to 1.
'          '~255' is out of range of the SByte type.
'       Conversions using CultureInfo:
'          Converted '-103' to -103.
'          Converted '+12' to 12.
'          Unable to parse '~16'.
'          Converted '  1' to 1.
'          Unable to parse '~255'.

注解

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

[ws][sign]数字[ws][ws][sign]digits[ws]

方括号 ([ and ]) 中的元素是可选的。Elements 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使用样式对参数进行解释 IntegerThe s parameter is interpreted using the Integer style. 除了字节值的十进制数字,只允许使用前导符号和尾随空格。In addition to the byte value's decimal digits, only leading and trailing spaces with a leading sign are allowed. 若要使用可以出现在中的区域性特定格式设置信息显式定义样式元素 s ,请使用 Parse(String, NumberStyles, IFormatProvider) 方法。To explicitly define the style elements with the culture-specific formatting information that can be present in s, use the Parse(String, NumberStyles, IFormatProvider) method.

provider参数是一个 IFormatProvider 实现,其 GetFormat 方法返回一个 NumberFormatInfo 对象,该对象提供有关格式的区域性特定信息 sThe provider parameter is an IFormatProvider implementation whose GetFormat method returns a NumberFormatInfo object that provides culture-specific information about the format of s. 使用 provider 参数为分析操作提供自定义格式设置信息的方法有三种:There are three ways to use the provider parameter to supply custom formatting information to the parse operation:

如果 providernull ,则 NumberFormatInfo 使用当前区域性的对象。If provider is null, the NumberFormatInfo object for the current culture is used.

另请参阅

适用于