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);
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.

傳回

8 位元帶正負號的位元組值,等於 s 參數中所指定的數字。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 的格式與 style不相容。s 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. 它必須是來自 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:

[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]

在方括號 ([ 和 ]) 中的項目是選擇性的項目。Elements in square brackets ([ and ]) are optional. 下表說明每個元素。The following table describes each element.

項目Element 說明Description
wsws 選擇性的空白字元。Optional white space. 如果 style 包含 NumberStyles.AllowLeadingWhite 旗標,則空格可以出現在 s 的開頭,如果 style 包含 NumberStyles.AllowTrailingWhite 旗標,它可以出現在 s 的結尾。White 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. 如果 style 包含 NumberStyles.AllowCurrencySymbol 旗標,則目前文化特性的貨幣符號可能會出現在 s 中。The current culture's currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
簽署sign 選擇性的正負號。An optional sign. 如果 style 包含 NumberStyles.AllowLeadingSign 旗標,則正負號可以出現在 s 的開頭,如果 style 包含 NumberStyles.AllowTrailingSign 旗標,它可以顯示 s 的結尾。The 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. 如果 style 包含 NumberStyles.AllowParentheses 旗標,則可以在 s 中使用括弧來表示負數值。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 decimal point symbol. 如果 style 包含 NumberStyles.AllowDecimalPoint 旗標,則目前文化特性的小數點符號可能會出現在 s 中。The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
fractional_digitsfractional_digits 如果 style 包含 NumberStyles.AllowExponent 旗標,則為數字0-9 的一個或多個專案,如果不是,則為數字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. 只有在 style 包含 NumberStyles.AllowDecimalPoint 旗標時,小數位數才會出現在 s 中。Fractional 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. 如果 style 包含 NumberStyles.AllowExponent 旗標,s 參數可以表示指數標記法中的數位。The 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. 如果 style 包含 NumberStyles.AllowExponent 旗標,s 參數可以表示指數標記法中的數位。The 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.

注意

不論 style 引數的值為何,剖析作業都會忽略 s 中的任何終止 NUL (U + 0000)字元。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 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 成員如何影響 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 小數點(.)和fractional_digits元素。The decimal point (.) and fractional_digits elements. 不過,如果樣式不包含 NumberStyles.AllowExponent 旗標, fractional_digits必須只包含一或多個0位數;否則,會擲回 OverflowExceptionHowever, 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 s開頭的ws元素。The ws element at the beginning of s.
NumberStyles.AllowTrailingWhite s結尾的ws元素。The 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 Currency ($)元素。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 物件,以提供有關 s格式的特定文化特性資訊。The 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:

如果 null``provider,則會使用目前文化特性的 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.

[System.CLSCompliant(false)]
public static sbyte Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider provider = null);
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 = null) 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.

傳回

8 位元帶正負號的位元組值,等於 s 參數中所指定的數字。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);
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.

傳回

8 位元帶正負號的整數,這個整數等於 s 中所指定的數字。An 8-bit signed integer that is equivalent to the number specified in s.

屬性

例外狀況

snulls is null.

s 的格式與 style 不相容。s 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.

範例

下列範例會使用 Parse(String, NumberStyles) 方法來剖析 SByte 值的字串表示。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. 它必須是來自 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:

[ws][$][sign]數位[。fractional_digits] [E [sign]exponential_digits] [ws][ws][$][sign]digits[.fractional_digits][E[sign]exponential_digits][ws]

如果 style 包含 NumberStyles.AllowHexSpecifiers 參數可能會包含下列元素:If style includes NumberStyles.AllowHexSpecifier, the s parameter may contain the following elements:

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

在方括號 ([ 和 ]) 中的項目是選擇性的項目。Elements in square brackets ([ and ]) are optional. 下表說明每個元素。The following table describes each element.

項目Element 說明Description
wsws 選擇性的空白字元。Optional white space. 如果 style 包含 NumberStyles.AllowLeadingWhite 旗標,則空格可以出現在 s 的開頭,如果 style 包含 NumberStyles.AllowTrailingWhite 旗標,它可以出現在 s 的結尾。White 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. 如果 style 包含 NumberStyles.AllowCurrencySymbol 旗標,則目前文化特性的貨幣符號可能會出現在 s 中。The current culture's currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
簽署sign 選擇性的正負號。An optional sign. 如果 style 包含 NumberStyles.AllowLeadingSign 旗標,則正負號可以出現在 s 的開頭,如果 style 包含 NumberStyles.AllowTrailingSign 旗標,它可以出現在 s 的結尾。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. 如果 style 包含 NumberStyles.AllowParentheses 旗標,則可以在 s 中使用括弧來表示負數值。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 decimal point symbol. 如果 style 包含 NumberStyles.AllowDecimalPoint 旗標,則目前文化特性的小數點符號可能會出現在 s 中。The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
fractional_digitsfractional_digits 如果 style 包含 NumberStyles.AllowExponent 旗標,則為數字0-9 的一個或多個專案,如果不是,則為數字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. 只有在 style 包含 NumberStyles.AllowDecimalPoint 旗標時,小數位數才會出現在 s 中。Fractional 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. 如果 style 包含 NumberStyles.AllowExponent 旗標,s 參數可以表示指數標記法中的數位。The 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. 如果 style 包含 NumberStyles.AllowExponent 旗標,s 參數可以表示指數標記法中的數位。The 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.

注意

不論 style 引數的值為何,剖析作業都會忽略 s 中的任何終止 NUL (U + 0000)字元。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 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 成員如何影響 s中可能存在的元素。The 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位數;否則,會擲回 OverflowExceptionHowever, 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 s開頭的ws元素。The ws element at the beginning of s.
NumberStyles.AllowTrailingWhite s結尾的ws元素。The ws element at the end of s.
NumberStyles.AllowLeadingSign 數位前的正號。A positive sign before digits.
NumberStyles.AllowTrailingSign 數位後的正號。A positive sign after digits.
NumberStyles.AllowParentheses 以括弧形式括住數值的sign元素。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 Currency ($)元素。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. 只有包含在 style 中的其他旗標可 NumberStyles.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);
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.

傳回

8 位元帶正負號的整數,這個整數等於 s 參數中所包含的數字。An 8-bit signed integer that is equivalent to the number contained in the s parameter.

屬性

例外狀況

snulls is null.

s 不是由選擇性正負號後面接著一連串數字 (零到九) 所組成。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.

範例

下列範例示範如何使用 Parse 方法,將字串值轉換成帶正負號的位元組值。The 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]

在方括號 ([ 和 ]) 中的項目是選擇性的項目。Elements in square brackets ([ and ]) are optional. 下表說明每個元素。The following table describes each element.

項目Element 說明Description
wsws 選擇性的空白字元。Optional white space.
簽署sign 選擇性的正負號。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 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);
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.

傳回

8 位元帶正負號的整數,這個整數等於 s 中所指定的數字。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]

在方括號 ([ 和 ]) 中的項目是選擇性的項目。Elements in square brackets ([ and ]) are optional. 下表說明每個元素。The following table describes each element.

項目Element 說明Description
wsws 選擇性的空白字元。Optional white space.
簽署sign 選擇性的正負號。An optional sign.
digitsdigits 範圍從0到9的數位序列。A sequence of digits ranging from 0 to 9.

s 參數會使用 Integer 樣式來加以解讀。The 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 物件,以提供有關 s格式的特定文化特性資訊。The 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:

如果 null``provider,則會使用目前文化特性的 NumberFormatInfo 物件。If provider is null, the NumberFormatInfo object for the current culture is used.

另請參閱

適用於