SByte.Parse 方法

定义

将数字的字符串表示形式转换为它的等效 8 位有符号整数。

重载

Parse(String, NumberStyles, IFormatProvider)

将指定样式和区域性特定格式的数字的字符串表示形式转换为它的等效 8 位有符号数值。

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

将指定样式和区域性特定格式的数字的范围表示形式转换为它的等效 8 位带符号数值。

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

将 UTF-8 字符范围分析为值。

Parse(String, IFormatProvider)

将指定的区域性特定格式的数字的字符串表示形式转换为它的等效 8 位有符号整数。

Parse(String)

将数字的字符串表示形式转换为它的等效 8 位有符号整数。

Parse(ReadOnlySpan<Char>, IFormatProvider)

将字符范围分析为值。

Parse(ReadOnlySpan<Byte>, IFormatProvider)

将 UTF-8 字符范围分析为值。

Parse(String, NumberStyles)

将指定样式的数字的字符串表示形式转换为它的等效 8 位有符号整数。

Parse(String, NumberStyles, IFormatProvider)

重要

此 API 不符合 CLS。

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

将指定样式和区域性特定格式的数字的字符串表示形式转换为它的等效 8 位有符号数值。

public:
 static System::SByte Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
 static System::SByte Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<System::SByte>::Parse;
[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

包含要转换的数字的字符串。 该字符串使用由 style 指定的样式来进行解释。

style
NumberStyles

枚举值的按位组合,用于指示可出现在 s 中的样式元素。 要指定的一个典型值为 Integer

provider
IFormatProvider

一个对象,提供有关 s 的区域性特定格式设置信息。 如果 providernull,则使用当前区域性。

返回

s 参数中指定的数字等效的 8 位有符号字节值。

实现

属性

例外

style 不是 NumberStyles 值。

- 或 -

style 不是 AllowHexSpecifierHexNumber 的组合。

snull

s 的格式不符合 style

s 表示小于 SByte.MinValue 或大于 SByte.MaxValue 的数字

- 或 -

s 包含非零的小数位。

示例

下面的示例演示如何使用 Parse(String, NumberStyles, IFormatProvider) 方法将数字的各种字符串表示形式转换为带符号整数值。

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
open System
open System.Globalization

let provider = NumberFormatInfo.CurrentInfo
   
let callParseOperation stringValue (style: NumberStyles) =
    if stringValue = null then
        printfn "Cannot parse a null string..."
    else
        try
            let number = SByte.Parse(stringValue, style)
            printfn $"SByte.Parse('{stringValue}', {style})) = {number}" 
        with
        | :? FormatException ->
            printfn $"'{stringValue}' and {style} throw a FormatException"
        | :? OverflowException ->
            printfn $"'{stringValue}' is outside the range of a signed byte"

[<EntryPoint>]
let main _ =
    let stringValue = "   123   "
    let style = NumberStyles.None     
    callParseOperation stringValue style
    
    let stringValue = "000,000,123"
    let style = NumberStyles.Integer ||| NumberStyles.AllowThousands
    callParseOperation stringValue style
    
    let stringValue = "-100"
    let style = NumberStyles.AllowLeadingSign
    callParseOperation stringValue style
    
    let stringValue = "100-"
    let style = NumberStyles.AllowLeadingSign
    callParseOperation stringValue style
    
    let stringValue = "100-"
    let style = NumberStyles.AllowTrailingSign
    callParseOperation stringValue style
    
    let stringValue = "$100"
    let style = NumberStyles.AllowCurrencySymbol
    callParseOperation stringValue style
    
    let style = NumberStyles.Integer
    callParseOperation stringValue style
    
    let style = NumberStyles.AllowDecimalPoint
    callParseOperation "100.0" style
    
    let stringValue = "1e02"
    let style = NumberStyles.AllowExponent
    callParseOperation stringValue style
    
    let stringValue = "(100)"
    let style = NumberStyles.AllowParentheses
    callParseOperation stringValue style
    0

// 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 允许分析操作成功。 它必须是 枚举中的位标志 NumberStyles 的组合。

根据 的值 styles 参数可能包括以下元素:

[ws][$][sign]digits[.fractional_digits][E[sign]exponential_digits][ws]

如果 style 包含 AllowHexSpecifier,则 s 参数可以包含以下元素:

[ws]hexdigits[ws]

方括号 ([ and ]) 中的元素是可选的。 下表对每个元素进行了描述。

元素 说明
ws 可选空格。 如果包含 标志,s则开头会出现空格;如果stylestyle包含 NumberStyles.AllowTrailingWhite 标志,则它可能出现在 末尾sNumberStyles.AllowLeadingWhite
$ 区域性特定的货币符号。 它在字符串中的位置由 NumberFormatInfo.CurrencyPositivePattern 当前区域性的 属性定义。 如果style包含 NumberStyles.AllowCurrencySymbol 标志,则当前区域性的货币符号可以出现在 中s
sign 可选符号。 如果style包含 标志,则符号可以出现在 的s开头;如果style包含 NumberStyles.AllowTrailingSign 标志,则它可以出现在 的sNumberStyles.AllowLeadingSign末尾。 如果style包含 标志,NumberStyles.AllowParentheses则可以在 中使用s括号来指示负值。
位数 从 0 到 9 的数字序列。
. 区域性特定的小数点符号。 如果style包含 NumberStyles.AllowDecimalPoint 标志,则当前区域性的小数点符号可以出现在 中s
fractional_digits 如果包含 NumberStyles.AllowExponent 标志,则style出现一个或多个数字 0-9,否则出现一个或多个数字 0。 仅当包含 标志时styleNumberStyles.AllowDecimalPoint小数位数才能显示在 中s
E “e”或“E”字符,指示该值以指数 (科学) 表示法表示。 如果style包含 标志,则 s 参数可以表示指数表示法中的NumberStyles.AllowExponent数字。
exponential_digits 从 0 到 9 的数字序列。 如果style包含 标志,则 s 参数可以表示指数表示法中的NumberStyles.AllowExponent数字。
hexdigits 从 0 到 f 或 0 到 F 的十六进制数字序列。

注意

分析操作将忽略中 s 任何 (U+0000) 字符的终止 NUL,而不考虑 参数的值 style

具有十进制数字的字符串仅 (对应于 NumberStyles.None 样式) 始终成功分析。 大多数剩余 NumberStyles 成员控制此输入字符串中可能存在但不需要存在的元素。 下表指示各个 NumberStyles 成员如何影响 中可能存在 s的元素。

非复合 NumberStyles 除数字外允许的 s 元素
NumberStyles.None 仅十进制数字。
NumberStyles.AllowDecimalPoint 小数点 (.) 和 fractional_digits 元素。 但是,如果 style 不包含 NumberStyles.AllowExponent 标志, fractional_digits 必须仅包含一个或多个 0 位数字;否则会 OverflowException 引发 。
NumberStyles.AllowExponent “e”或“E”字符,指示指数表示法以及 exponential_digits
NumberStyles.AllowLeadingWhite 开头的 sws 元素。
NumberStyles.AllowTrailingWhite 位于 末尾的 sws 元素。
NumberStyles.AllowLeadingSign 数字前的正号。
NumberStyles.AllowTrailingSign 数字后的正号。
NumberStyles.AllowParentheses 数字前后的括号表示负值。
NumberStyles.AllowThousands 组分隔符 () 元素。 虽然组分隔符可以出现在 中 s,但它前面必须只有一个或多个 0 位数字。
NumberStyles.AllowCurrencySymbol 元素 ($) 货币。

如果使用标志 NumberStyles.AllowHexSpecifiers 必须是十六进制值。 有效的十六进制数字为 0-9、a-f 和 A-F。 唯一可以与其组合的其他标志是 NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhite。 (枚举 NumberStyles 包含复合数字样式 NumberStyles.HexNumber,其中包含空格标志 )

注意

s如果 参数是十六进制数的字符串表示形式,则它前面不能有任何修饰 (如 0x&h) ,以将其区分为十六进制数。 这会导致分析操作引发异常。

如果 s 表示十六进制数,则 Parse(String, NumberStyles) 方法将字节的高阶位解释为符号位。

provider参数是一个IFormatProvider实现,其GetFormat方法返回一个 NumberFormatInfo 对象,该对象提供有关 格式的s区域性特定信息。 有三种方法可以使用 provider 参数向分析操作提供自定义格式设置信息:

如果 providernull,则 NumberFormatInfo 使用当前区域性的 对象。

适用于

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

重要

此 API 不符合 CLS。

将指定样式和区域性特定格式的数字的范围表示形式转换为它的等效 8 位带符号数值。

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>

一个范围,包含表示要转换的数字的字符。 该范围使用由 style 指定的样式来进行解释。

style
NumberStyles

枚举值的按位组合,用于指示可出现在 s 中的样式元素。 要指定的一个典型值为 Integer

provider
IFormatProvider

一个对象,提供有关 s 的区域性特定格式设置信息。 如果 providernull,则使用当前区域性。

返回

s 参数中指定的数字等效的 8 位有符号字节值。

实现

属性

适用于

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

将 UTF-8 字符范围分析为值。

public static sbyte Parse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> sbyte
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As SByte

参数

utf8Text
ReadOnlySpan<Byte>

要分析的 UTF-8 字符的跨度。

style
NumberStyles

可以存在于 中的 utf8Text数字样式的按位组合。

provider
IFormatProvider

一个对象,提供有关 utf8Text 的区域性特定格式设置信息。

返回

分析 utf8Text的结果。

实现

适用于

Parse(String, IFormatProvider)

重要

此 API 不符合 CLS。

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

将指定的区域性特定格式的数字的字符串表示形式转换为它的等效 8 位有符号整数。

public:
 static System::SByte Parse(System::String ^ s, IFormatProvider ^ provider);
public:
 static System::SByte Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<System::SByte>::Parse;
[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

表示要转换的数字的字符串。 该字符串使用 Integer 样式来进行解释。

provider
IFormatProvider

一个对象,提供有关 s 的区域性特定格式设置信息。 如果 providernull,则使用当前区域性。

返回

s 中指定的数字等效的 8 位有符号整数。

实现

属性

例外

snull

s 的格式不正确。

示例

以下示例定义了一个自定义 NumberFormatInfo 对象,该对象将平铺 (~) 定义为负号。 然后,它使用此自定义 NumberFormatInfo 对象以及 CultureInfo 表示固定区域性的对象来分析多个数字字符串。

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'.
open System
open System.Globalization

let nf = NumberFormatInfo()
nf.NegativeSign <- "~" 

let values = [| "-103"; "+12"; "~16"; "  1"; "~255" |]
let providers: IFormatProvider[] = [| nf; CultureInfo.InvariantCulture |]

for provider in providers do
    printfn $"Conversions using {(box provider).GetType().Name}:"
    for value in values do
        try
            printfn $"   Converted '{value}' to {SByte.Parse(value, provider)}."
        with
        | :? FormatException ->
            printfn $"   Unable to parse '{value}'."
        | :? OverflowException ->
            printfn $"   '{value}' is out of range of the SByte type."

// 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 包含以下形式的一些:

[ws][sign]digits[ws]

方括号 ([ and ]) 中的元素是可选的。 下表对每个元素进行了描述。

元素 说明
ws 可选空格。
sign 可选符号。
位数 数字序列,范围从 0 到 9。

参数 s 使用 Integer 样式进行解释。 除了字节值的十进制数字之外,仅允许使用带前导符号的前导空格和尾随空格。 若要使用 中存在的 s特定于区域性的格式设置信息显式定义样式元素,请使用 Parse(String, NumberStyles, IFormatProvider) 方法。

provider参数是一个IFormatProvider实现,其GetFormat方法返回一个 NumberFormatInfo 对象,该对象提供有关 格式的s区域性特定信息。 有三种方法可以使用 provider 参数向分析操作提供自定义格式设置信息:

如果 providernull,则 NumberFormatInfo 使用当前区域性的 对象。

另请参阅

适用于

Parse(String)

重要

此 API 不符合 CLS。

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

将数字的字符串表示形式转换为它的等效 8 位有符号整数。

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

表示要转换的数字的字符串。 该字符串使用 Integer 样式来进行解释。

返回

s 参数中包含的数字等效的 8 位有符号整数。

属性

例外

snull

s 不是由一个可选符号后跟一系列数字 (0-9) 组成的。

示例

以下示例演示如何使用 Parse 方法将字符串值转换为带符号字节值。 然后将生成的有符号字节值显示到控制台。

// 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.
open System

// Define an array of numeric strings.
let values = 
    [| "-16"; "  -3"; "+ 12"; " +12 "; "  12  "
       "+120"; "(103)"; "192"; "-160" |]
                            
// Parse each string and display the result.
for value in values do
    try
        printfn $"Converted '{value}' to the SByte value {SByte.Parse value}."
    with
    | :? FormatException ->
        printfn $"'{value}' cannot be parsed successfully by SByte type."
    | :? OverflowException ->
        printfn $"'{value}' is out of range of the SByte type."
        
// 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 包含以下形式的一些:

[ws][sign]digits[ws]

方括号 ([ and ]) 中的元素是可选的。 下表对每个元素进行了描述。

元素 说明
ws 可选空格。
sign 可选符号。
位数 数字序列,范围从 0 到 9。

参数 s 使用 NumberStyles.Integer 样式进行解释。 除了字节值的十进制数字之外,只允许使用前导正号或负号的前导空格和尾随空格。 若要显式定义可以存在于 中的 s样式元素,请使用 Parse(String, NumberStyles)Parse(String, NumberStyles, IFormatProvider) 方法。

通过使用 s 中为当前系统区域性初始化的格式信息 NumberFormatInfo 来分析 参数。 有关详细信息,请参阅 NumberFormatInfo.CurrentInfo。 若要使用其他区域性的格式设置信息来分析字符串,请使用 Parse(String, NumberStyles, IFormatProvider) 方法。

另请参阅

适用于

Parse(ReadOnlySpan<Char>, IFormatProvider)

将字符范围解析为值。

public:
 static System::SByte Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<System::SByte>::Parse;
public static sbyte Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> sbyte
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As SByte

参数

s
ReadOnlySpan<Char>

要分析的字符范围。

provider
IFormatProvider

一个对象,提供有关 s 的区域性特定格式设置信息。

返回

分析 s的结果。

实现

适用于

Parse(ReadOnlySpan<Byte>, IFormatProvider)

将 UTF-8 字符范围分析为值。

public:
 static System::SByte Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<System::SByte>::Parse;
public static sbyte Parse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> sbyte
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As SByte

参数

utf8Text
ReadOnlySpan<Byte>

要分析的 UTF-8 字符的跨度。

provider
IFormatProvider

一个对象,提供有关 utf8Text 的区域性特定格式设置信息。

返回

分析 utf8Text的结果。

实现

适用于

Parse(String, NumberStyles)

重要

此 API 不符合 CLS。

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

将指定样式的数字的字符串表示形式转换为它的等效 8 位有符号整数。

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

包含要转换的数字的字符串。 该字符串使用由 style 指定的样式来进行解释。

style
NumberStyles

枚举值的按位组合,用于指示可出现在 s 中的样式元素。 要指定的一个典型值为 Integer

返回

s 中指定的数字等效的 8 位有符号整数。

属性

例外

snull

s 的格式不符合 style

s 表示小于 SByte.MinValue 或大于 SByte.MaxValue 的数字

- 或 -

s 包含非零的小数位。

style 不是 NumberStyles 值。

- 或 -

style 不是 AllowHexSpecifierHexNumber 值的组合。

示例

以下示例使用 Parse(String, NumberStyles) 方法分析值的字符串表示形式SByte。 本示例的当前区域性为 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.
open System
open System.Globalization

// Parse value with no styles allowed.
let values1 = [| " 121 "; "121"; "-121" |]
let style = NumberStyles.None
printfn $"Styles: {style}"
for value in values1 do
    try
        let number = SByte.Parse(value, style)
        printfn $"   Converted '{value}' to {number}."
    with :? FormatException ->
        printfn $"   Unable to parse '{value}'."
printfn ""
            
// Parse value with trailing sign.
let style2 = NumberStyles.Integer ||| NumberStyles.AllowTrailingSign
let values2 = [| " 103+"; " 103 +"; "+103"; "(103)"; "   +103  " |]
printfn $"Styles: {style2}"
for value in values2 do
    try
        let number = SByte.Parse(value, style2)
        printfn $"   Converted '{value}' to {number}."
    with 
    | :? FormatException ->
        printfn $"   Unable to parse '{value}'."
    | :? OverflowException ->
        printfn $"   '{value}' is out of range of the SByte type."         
printfn ""
// 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 允许分析操作成功。 它必须是枚举中的位标志 NumberStyles 的组合。

根据 的值 styles 参数可能包含以下元素:

[ws][$][sign]digits[.fractional_digits][E[sign]exponential_digits][ws]

如果 style 包含 NumberStyles.AllowHexSpecifier,则 s 参数可以包含以下元素:

[ws]hexdigits[ws]

方括号 ([ and ]) 中的元素是可选的。 下表对每个元素进行了描述。

元素 说明
ws 可选空格。 如果style包含标志,则空白可以显示在 的开头s,如果样式包含NumberStyles.AllowTrailingWhite标志,则它可能会出现在 sNumberStyles.AllowLeadingWhite 末尾。
$ 区域性特定的货币符号。 它在字符串中的位置由 NumberFormatInfo.CurrencyPositivePattern 当前区域性的 属性定义。 如果包含 标志,则当前区域性的货币符号可以显示在 中sNumberStyles.AllowCurrencySymbolstyle
sign 可选符号。 如果style包含 标志,则符号可以出现在 的s开头,如果style包含 NumberStyles.AllowTrailingSign 标志,则它可以显示在 sNumberStyles.AllowLeadingSign 末尾。 如果style包含 NumberStyles.AllowParentheses 标志,则可以在 中使用s括号来指示负值。
位数 从 0 到 9 的数字序列。
. 区域性特定的小数点符号。 如果style包含 标志,则当前区域性的小数点符号会显示在 NumberStyles.AllowDecimalPoints
fractional_digits 如果包含 NumberStyles.AllowExponent 标志,则出现一个或多个数字 0-9;如果style不包含标志,则出现一个或多个数字 0。 仅当包含 NumberStyles.AllowDecimalPoint 标志时style,小数位数才能显示在 中s
E “e”或“E”字符,指示值以指数 (科学) 表示法表示。 如果style包含 标志,参数s可以表示指数表示法的数字NumberStyles.AllowExponent
exponential_digits 数字 0-9 的一个或多个匹配项。 如果style包含 标志,参数s可以表示指数表示法的数字NumberStyles.AllowExponent
hexdigits 从 0 到 f 或 0 到 F 的十六进制数字序列。

注意

分析操作将忽略中 s 任何 (U+0000) 字符的终止 NUL,而不考虑参数的值 style

仅具有十进制数字的字符串 (,它与) 始终成功分析的样式相对应 NumberStyles.None 。 大多数剩余 NumberStyles 成员控制可能存在于输入字符串中但不需要存在的元素。 下表指示各个 NumberStyles 成员如何影响 中可能存在的 s元素。

非复合 NumberStyles 值 除数字外允许 元素
NumberStyles.None 仅十进制数字。
NumberStyles.AllowDecimalPoint 小数点 (.) 和 fractional_digits 元素。 但是,如果 style 不包含 NumberStyles.AllowExponent 标志, fractional_digits 必须只包含一个或多个 0 位;否则将 OverflowException 引发 。
NumberStyles.AllowExponent 指示指数表示法的“e”或“E”字符以及 exponential_digits
NumberStyles.AllowLeadingWhite 开头的 sws 元素。
NumberStyles.AllowTrailingWhite 末尾的 sws 元素。
NumberStyles.AllowLeadingSign 数字前的正
NumberStyles.AllowTrailingSign 数字后的正号。
NumberStyles.AllowParentheses 以括号形式将数值括起来的 符号 元素。
NumberStyles.AllowThousands 组分隔符 (,) 元素。 虽然组分隔符可以出现在 中 s,但它的前面必须只有一个或多个 0 位。
NumberStyles.AllowCurrencySymbol 货币 ($) 元素。

如果使用标志 NumberStyles.AllowHexSpecifiers 则必须是十六进制值。 有效的十六进制数字为 0-9、a-f 和 A-F。 不支持“0x”等前缀,导致分析操作失败。 唯一可以合并的其他 style 标志是 NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhite。 (枚举 NumberStyles 包含复合数字样式 , NumberStyles.HexNumber其中包含两个空格标志。)

注意

s如果 参数是十六进制数的字符串表示形式,则它前面不能有任何修饰 (,如 0x&h) ,以将其区分为十六进制数。 这会导致分析操作引发异常。

如果 s 表示十六进制数,则 Parse(String, NumberStyles) 方法将字节的高阶位解释为符号位。

参数 s 是使用为当前系统区域性初始化的 对象中的 NumberFormatInfo 格式设置信息进行分析的。 若要使用其他区域性的格式设置信息,请调用 Parse(String, NumberStyles, IFormatProvider) 重载。

另请参阅

适用于