SByte.Parse Metoda

Definicja

Konwertuje ciąg reprezentujący liczbę na odpowiadającą mu 8-bitową liczbę całkowitą ze znakiem.

Przeciążenia

Parse(String, NumberStyles, IFormatProvider)

Konwertuje reprezentację ciągu liczby w określonym stylu i formacie specyficznym dla kultury na odpowiednik z podpisem 8-bitowym.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Konwertuje reprezentację zakresu liczby w określonym stylu i formacie specyficznym dla kultury na odpowiednik z podpisem 8-bitowym.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Analizuje zakres znaków UTF-8 w wartość.

Parse(String, IFormatProvider)

Konwertuje reprezentację ciągu liczby w określonym formacie specyficznym dla kultury na odpowiednik liczby całkowitej ze znakiem 8-bitowym.

Parse(String)

Konwertuje ciąg reprezentujący liczbę na odpowiadającą mu 8-bitową liczbę całkowitą ze znakiem.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Analizuje zakres znaków w wartości.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Analizuje zakres znaków UTF-8 w wartość.

Parse(String, NumberStyles)

Konwertuje reprezentację ciągu liczby w określonym stylu na odpowiednik 8-bitowej liczby całkowitej ze znakiem 8-bitowym.

Parse(String, NumberStyles, IFormatProvider)

Źródło:
SByte.cs
Źródło:
SByte.cs
Źródło:
SByte.cs

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

Alternatywa zgodna ze specyfikacją CLS
System.Int16.Parse(String, NumberStyles, IFormatProvider)

Konwertuje reprezentację ciągu liczby w określonym stylu i formacie specyficznym dla kultury na odpowiednik z podpisem 8-bitowym.

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

Parametry

s
String

Ciąg zawierający liczbę, którą należy przekształcić. Ciąg jest interpretowany przy użyciu stylu określonego przez style.

style
NumberStyles

Bitowa kombinacja wartości wyliczenia, która wskazuje elementy stylu, które mogą być obecne w sobiekcie . Typową wartością do określenia jest Integer.

provider
IFormatProvider

Obiekt, który dostarcza informacje o formatowaniu specyficznym dla kultury.s Jeśli provider jest to null, używana jest bieżąca kultura wątku.

Zwraca

8-bitowa podpisana wartość bajtu, która jest równoważna liczbie określonej w parametrze s .

Implementuje

Atrybuty

Wyjątki

style nie jest wartością NumberStyles .

-lub-

style nie jest kombinacją elementów AllowHexSpecifier i HexNumber.

s nie jest w formacie zgodnym z programem style.

s reprezentuje liczbę, która jest mniejsza niż SByte.MinValue lub większa niż SByte.MaxValue.

-lub-

s zawiera cyfry niezerowe, ułamkowe.

Przykłady

Poniższy przykład ilustruje użycie Parse(String, NumberStyles, IFormatProvider) metody do konwertowania różnych reprezentacji ciągów liczb na podpisane wartości całkowite.

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

Uwagi

Parametr style definiuje elementy stylu (takie jak biały odstęp lub symbol znaku dodatniego lub ujemnego), które są dozwolone w parametrze s operacji analizowania, aby operacja analizy zakończyła się powodzeniem. Musi być kombinacją flag bitowych z wyliczenia NumberStyles .

W zależności od wartości parametr może styles zawierać następujące elementy:

[ws] [][$znak]cyfry[.fractional_digits][E[znak]exponential_digits][ws]

Jeśli style parametr zawiera AllowHexSpecifierparametr , s może zawierać następujące elementy:

[ws] hexdigits[ws]

Elementy w nawiasach kwadratowych ([ i ]) są opcjonalne. W tabeli poniżej opisano każdy element.

Element Opis
Ws Opcjonalny odstęp. Biały odstęp może pojawić się na początku s , jeśli style zawiera flagę NumberStyles.AllowLeadingWhite i może pojawić się na końcu s , jeśli style zawiera flagę NumberStyles.AllowTrailingWhite .
$ Symbol waluty specyficzny dla kultury. Jego pozycja w ciągu jest definiowana przez NumberFormatInfo.CurrencyPositivePattern właściwość bieżącej kultury. Symbol waluty bieżącej kultury może być wyświetlany, s jeśli style zawiera flagę NumberStyles.AllowCurrencySymbol .
sign Opcjonalny znak. Znak może pojawić się na początku, jeśli zawiera flagę i może pojawić się na końcu ss, jeśli style zawiera flagęNumberStyles.AllowTrailingSign.NumberStyles.AllowLeadingSignstyle Nawiasy mogą służyć do wskazywania wartości ujemnej, s jeśli style zawiera flagę NumberStyles.AllowParentheses .
Cyfr Sekwencja cyfr od 0 do 9.
. Symbol dziesiętny specyficzny dla kultury. Symbol punktu dziesiętnego bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowDecimalPoint .
fractional_digits Co najmniej jedno wystąpienie cyfry 0–9, jeśli style zawiera flagę NumberStyles.AllowExponent lub co najmniej jedno wystąpienie cyfry 0, jeśli nie. Cyfry ułamkowe mogą być wyświetlane tylko wtedy s , gdy style zawiera flagę NumberStyles.AllowDecimalPoint .
E Znak „e” lub „E”, który wskazuje, że wartość jest reprezentowana w zapisie wykładniczym (naukowym). Parametr s może reprezentować liczbę w notacji wykładniczej, jeśli style zawiera flagę NumberStyles.AllowExponent .
exponential_digits Sekwencja cyfr od 0 do 9. Parametr s może reprezentować liczbę w notacji wykładniczej, jeśli style zawiera flagę NumberStyles.AllowExponent .
hexdigits Sekwencja cyfr szesnastkowych od 0 do f lub od 0 do F.

Uwaga

Wszelkie znaki zakończenia NUL (U+0000) w obiekcie s są ignorowane przez operację analizowania, niezależnie od wartości argumentu style .

Ciąg z cyframi dziesiętnymi (który odpowiada NumberStyles.None stylowi) zawsze analizuje się pomyślnie. Większość pozostałych NumberStyles elementów członkowskich kontrolki, które mogą być obecne, ale nie są wymagane do obecności, w tym ciągu wejściowym. Poniższa tabela wskazuje, jak poszczególne NumberStyles elementy członkowskie wpływają na elementy, które mogą być obecne w elemecie s.

Wartości nieskładne NumberStyles Elementy dozwolone s oprócz cyfr
NumberStyles.None Tylko cyfry dziesiętne.
NumberStyles.AllowDecimalPoint Elementy dziesiętne (.) i fractional_digits . Jeśli jednak styl nie zawiera flagi NumberStyles.AllowExponent , fractional_digits musi składać się tylko z jednej lub kilku cyfr; w przeciwnym razie OverflowException jest zgłaszana wartość .
NumberStyles.AllowExponent Znak "e" lub "E", który wskazuje notację wykładniczą wraz z exponential_digits.
NumberStyles.AllowLeadingWhite Element ws na początku s.
NumberStyles.AllowTrailingWhite Element ws na końcu selementu .
NumberStyles.AllowLeadingSign Znak dodatni przed cyframi.
NumberStyles.AllowTrailingSign Znak dodatni po cyfrach.
NumberStyles.AllowParentheses Nawiasy przed cyframi i po nich wskazują wartość ujemną.
NumberStyles.AllowThousands Element separatora grupy (,). Chociaż separator grupy może być wyświetlany w spliku , musi być poprzedzony tylko jedną lub większą 0 cyframi.
NumberStyles.AllowCurrencySymbol Element waluty ($).

Jeśli jest używana flaga NumberStyles.AllowHexSpecifier , s musi być wartością szesnastkową. Prawidłowe cyfry szesnastkowe to 0–9, a-f i A-F. Jedyną inną flagą, którą można połączyć z nim, są NumberStyles.AllowLeadingWhite i NumberStyles.AllowTrailingWhite. (Wyliczenie NumberStyles zawiera styl liczb złożonych, NumberStyles.HexNumber, który zawiera obie flagi odstępu).

Uwaga

s Jeśli parametr jest reprezentacją ciągu liczby szesnastkowej, nie może być poprzedzony żadną dekoracją (taką jak 0x lub &h), która rozróżnia ją jako liczbę szesnastkową. To powoduje zgłoszenie wyjątku przez operację analizy.

Jeśli s reprezentuje liczbę szesnastkową, Parse(String, NumberStyles) metoda interpretuje bit o wysokiej kolejności bajtu jako bit znaku.

Parametr provider jest implementacją IFormatProvider , której GetFormat metoda zwraca NumberFormatInfo obiekt, który dostarcza informacji specyficznych dla kultury dotyczących formatu s. Istnieją trzy sposoby używania parametru provider do podawania niestandardowych informacji o formatowaniu do operacji analizowania:

  • Możesz przekazać rzeczywisty NumberFormatInfo obiekt, który udostępnia informacje o formatowaniu. (Jego implementacja GetFormat po prostu zwraca się).

  • Można przekazać obiekt określający kulturę CultureInfo , której formatowanie ma być używane. Jego NumberFormat właściwość udostępnia informacje o formatowaniu.

  • Implementację niestandardową IFormatProvider można przekazać. Metoda GetFormat musi utworzyć wystąpienie i zwrócić NumberFormatInfo obiekt, który dostarcza informacje o formatowaniu.

Jeśli provider jest to null, NumberFormatInfo używany jest obiekt bieżącej kultury.

Dotyczy

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Źródło:
SByte.cs
Źródło:
SByte.cs
Źródło:
SByte.cs

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

Konwertuje reprezentację zakresu liczby w określonym stylu i formacie specyficznym dla kultury na odpowiednik z podpisem 8-bitowym.

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

Parametry

s
ReadOnlySpan<Char>

Zakres zawierający znaki reprezentujące liczbę do przekonwertowania. Zakres jest interpretowany przy użyciu stylu określonego przez style.

style
NumberStyles

Bitowa kombinacja wartości wyliczenia, która wskazuje elementy stylu, które mogą być obecne w sobiekcie . Typową wartością do określenia jest Integer.

provider
IFormatProvider

Obiekt, który dostarcza informacje o formatowaniu specyficznym dla kultury.s Jeśli provider jest to null, używana jest bieżąca kultura wątku.

Zwraca

8-bitowa podpisana wartość bajtu, która jest równoważna liczbie określonej w parametrze s .

Implementuje

Atrybuty

Dotyczy

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Źródło:
SByte.cs
Źródło:
SByte.cs

Analizuje zakres znaków UTF-8 w wartość.

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

Parametry

utf8Text
ReadOnlySpan<Byte>

Zakres znaków UTF-8 do przeanalizowania.

style
NumberStyles

Bitowa kombinacja stylów liczbowych, które mogą być obecne w obiekcie utf8Text.

provider
IFormatProvider

Obiekt, który udostępnia informacje o formatowaniu specyficznym dla kultury dotyczące utf8Textelementu .

Zwraca

Wynik analizy utf8Text.

Implementuje

Dotyczy

Parse(String, IFormatProvider)

Źródło:
SByte.cs
Źródło:
SByte.cs
Źródło:
SByte.cs

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

Alternatywa zgodna ze specyfikacją CLS
System.Int16.Parse(String)

Konwertuje reprezentację ciągu liczby w określonym formacie specyficznym dla kultury na odpowiednik liczby całkowitej ze znakiem 8-bitowym.

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

Parametry

s
String

Ciąg reprezentujący liczbę do konwersji. Ciąg jest interpretowany przy użyciu Integer stylu.

provider
IFormatProvider

Obiekt, który dostarcza informacje o formatowaniu specyficznym dla kultury.s Jeśli provider jest to null, używana jest bieżąca kultura wątku.

Zwraca

Liczba całkowita z podpisem 8-bitowym, która jest równoważna liczbie określonej w elemencie s.

Implementuje

Atrybuty

Wyjątki

s nie jest w poprawnym formacie.

s reprezentuje liczbę mniejszą niż SByte.MinValue lub większą niż SByte.MaxValue.

Przykłady

W poniższym przykładzie zdefiniowano obiekt niestandardowy NumberFormatInfo , który definiuje tilde (~) jako znak ujemny. Następnie analizuje liczbę ciągów liczbowych przy użyciu tego obiektu niestandardowego NumberFormatInfo , a także CultureInfo obiektu, który reprezentuje niezmienną kulturę.

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'.

Uwagi

Parametr s zawiera liczbę formularzy:

[ws] [znak] cyfry[ws]

Elementy w nawiasach kwadratowych ([ i ]) są opcjonalne. W tabeli poniżej opisano każdy element.

Element Opis
Ws Opcjonalny odstęp.
sign Opcjonalny znak.
Cyfr Sekwencja cyfr od 0 do 9.

Parametr s jest interpretowany przy użyciu Integer stylu. Oprócz cyfr dziesiętnych wartości bajtowej dozwolone są tylko spacje wiodące i końcowe z znakiem wiodącym. Aby jawnie zdefiniować elementy stylu przy użyciu informacji o formatowaniu specyficznym dla kultury, które mogą być obecne w sprogramie , użyj Parse(String, NumberStyles, IFormatProvider) metody .

Parametr provider jest implementacją IFormatProvider , której GetFormat metoda zwraca NumberFormatInfo obiekt, który dostarcza informacji specyficznych dla kultury dotyczących formatu s. Istnieją trzy sposoby używania parametru provider do podawania niestandardowych informacji o formatowaniu do operacji analizowania:

  • Możesz przekazać rzeczywisty NumberFormatInfo obiekt, który udostępnia informacje o formatowaniu. (Jego implementacja GetFormat po prostu zwraca się).

  • Można przekazać obiekt określający kulturę CultureInfo , której formatowanie ma być używane. Jego NumberFormat właściwość udostępnia informacje o formatowaniu.

  • Implementację niestandardową IFormatProvider można przekazać. Metoda GetFormat musi utworzyć wystąpienie i zwrócić NumberFormatInfo obiekt, który dostarcza informacje o formatowaniu.

Jeśli provider jest to null, NumberFormatInfo używany jest obiekt bieżącej kultury.

Zobacz też

Dotyczy

Parse(String)

Źródło:
SByte.cs
Źródło:
SByte.cs
Źródło:
SByte.cs

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

Alternatywa zgodna ze specyfikacją CLS
System.Int16.Parse(String)

Konwertuje ciąg reprezentujący liczbę na odpowiadającą mu 8-bitową liczbę całkowitą ze znakiem.

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

Parametry

s
String

Ciąg reprezentujący liczbę do konwersji. Ciąg jest interpretowany przy użyciu Integer stylu.

Zwraca

Liczba całkowita z podpisem 8-bitowym, która jest równoważna liczbie zawartej w parametrze s .

Atrybuty

Wyjątki

s to null.

s nie składa się z opcjonalnego znaku, po którym następuje sekwencja cyfr (od zera do dziewięciu).

s reprezentuje liczbę mniejszą niż SByte.MinValue lub większą niż SByte.MaxValue.

Przykłady

W poniższym przykładzie pokazano, jak przekonwertować wartość ciągu na podpisaną wartość bajtu Parse przy użyciu metody . Wynikowa wartość bajtu podpisanego jest następnie wyświetlana w konsoli programu .

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

Uwagi

Parametr s zawiera liczbę formularzy:

[ws] [znak] cyfry[ws]

Elementy w nawiasach kwadratowych ([ i ]) są opcjonalne. W tabeli poniżej opisano każdy element.

Element Opis
Ws Opcjonalny odstęp.
sign Opcjonalny znak.
Cyfr Sekwencja cyfr od 0 do 9.

Parametr s jest interpretowany przy użyciu NumberStyles.Integer stylu. Oprócz cyfr dziesiętnych wartości bajtowej dozwolone są tylko spacje wiodące i końcowe z wiodącym lub ujemnym znakiem. Aby jawnie zdefiniować elementy stylu, które mogą być obecne w sprogramie , użyj Parse(String, NumberStyles) metody lub Parse(String, NumberStyles, IFormatProvider) .

Parametr s jest analizowany przy użyciu informacji o formatowaniu w elemencie zainicjowanym NumberFormatInfo dla bieżącej kultury systemu. Aby uzyskać więcej informacji, zobacz NumberFormatInfo.CurrentInfo. Aby przeanalizować ciąg przy użyciu informacji o formatowaniu innej kultury, użyj Parse(String, NumberStyles, IFormatProvider) metody .

Zobacz też

Dotyczy

Parse(ReadOnlySpan<Char>, IFormatProvider)

Źródło:
SByte.cs
Źródło:
SByte.cs
Źródło:
SByte.cs

Analizuje zakres znaków w wartości.

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

Parametry

s
ReadOnlySpan<Char>

Zakres znaków do przeanalizowania.

provider
IFormatProvider

Obiekt, który udostępnia informacje o formatowaniu specyficznym dla kultury dotyczące selementu .

Zwraca

Wynik analizy s.

Implementuje

Dotyczy

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Źródło:
SByte.cs
Źródło:
SByte.cs

Analizuje zakres znaków UTF-8 w wartość.

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

Parametry

utf8Text
ReadOnlySpan<Byte>

Zakres znaków UTF-8 do przeanalizowania.

provider
IFormatProvider

Obiekt, który udostępnia informacje o formatowaniu specyficznym dla kultury dotyczące utf8Textelementu .

Zwraca

Wynik analizy utf8Text.

Implementuje

Dotyczy

Parse(String, NumberStyles)

Źródło:
SByte.cs
Źródło:
SByte.cs
Źródło:
SByte.cs

Ważne

Ten interfejs API nie jest zgodny ze specyfikacją CLS.

Alternatywa zgodna ze specyfikacją CLS
System.Int16.Parse(String)

Konwertuje reprezentację ciągu liczby w określonym stylu na odpowiednik 8-bitowej liczby całkowitej ze znakiem 8-bitowym.

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

Parametry

s
String

Ciąg zawierający liczbę, którą należy przekształcić. Ciąg jest interpretowany przy użyciu stylu określonego przez style.

style
NumberStyles

Bitowa kombinacja wartości wyliczenia, która wskazuje elementy stylu, które mogą być obecne w sobiekcie . Typową wartością do określenia jest Integer.

Zwraca

Liczba całkowita z podpisem 8-bitowym, która jest równoważna liczbie określonej w elemencie s.

Atrybuty

Wyjątki

s nie jest w formacie zgodnym z programem style.

s reprezentuje liczbę mniejszą niż SByte.MinValue lub większą niż SByte.MaxValue.

-lub-

s zawiera cyfry niezerowe, ułamkowe.

style nie jest wartością NumberStyles .

-lub-

style nie jest kombinacją AllowHexSpecifier wartości i HexNumber .

Przykłady

Poniższy przykład analizuje reprezentacje ciągów SByte wartości za pomocą Parse(String, NumberStyles) metody . W przykładzie bieżącą kulturą jest 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.

Uwagi

Parametr style definiuje elementy stylu (takie jak biały odstęp lub symbol znaku dodatniego lub ujemnego), które są dozwolone w parametrze s operacji analizowania, aby operacja analizy zakończyła się powodzeniem. Musi być kombinacją flag bitowych z wyliczenia NumberStyles .

W zależności od wartości parametr może styles zawierać następujące elementy:

[ws] [][$znak]cyfry[.fractional_digits][E[znak]exponential_digits][ws]

Jeśli style parametr zawiera NumberStyles.AllowHexSpecifierparametr , s może zawierać następujące elementy:

[ws] hexdigits[ws]

Elementy w nawiasach kwadratowych ([ i ]) są opcjonalne. W tabeli poniżej opisano każdy element.

Element Opis
Ws Opcjonalny odstęp. Biały znak może pojawić się na początku, jeśli style zawiera flagę NumberStyles.AllowLeadingWhite i może pojawić się na końcus, jeśli styl zawiera flagęNumberStyles.AllowTrailingWhite.s
$ Symbol waluty specyficzny dla kultury. Jego pozycja w ciągu jest definiowana przez NumberFormatInfo.CurrencyPositivePattern właściwość bieżącej kultury. Symbol waluty bieżącej kultury może być wyświetlany, s jeśli style zawiera flagę NumberStyles.AllowCurrencySymbol .
sign Opcjonalny znak. Znak może pojawić się na początku s , jeśli style zawiera flagę NumberStyles.AllowLeadingSign i może pojawić się na końcu s , jeśli style zawiera flagę NumberStyles.AllowTrailingSign . Nawiasy mogą służyć do wskazywania wartości ujemnej, s jeśli style zawiera flagę NumberStyles.AllowParentheses .
Cyfr Sekwencja cyfr od 0 do 9.
. Symbol dziesiętny specyficzny dla kultury. Symbol punktu dziesiętnego bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowDecimalPoint .
fractional_digits Co najmniej jedno wystąpienie cyfry 0–9, jeśli style zawiera flagę NumberStyles.AllowExponent lub co najmniej jedno wystąpienie cyfry 0, jeśli nie. Cyfry ułamkowe mogą być wyświetlane tylko wtedy s , gdy style zawiera flagę NumberStyles.AllowDecimalPoint .
E Znak „e” lub „E”, który wskazuje, że wartość jest reprezentowana w zapisie wykładniczym (naukowym). Parametr s może reprezentować liczbę w notacji wykładniczej, jeśli style zawiera flagę NumberStyles.AllowExponent .
exponential_digits Co najmniej jedno wystąpienie cyfry 0–9. Parametr s może reprezentować liczbę w notacji wykładniczej, jeśli style zawiera flagę NumberStyles.AllowExponent .
hexdigits Sekwencja cyfr szesnastkowych od 0 do f lub od 0 do F.

Uwaga

Wszelkie znaki zakończenia NUL (U+0000) w obiekcie s są ignorowane przez operację analizowania, niezależnie od wartości argumentu style .

Ciąg z cyframi dziesiętnymi (który odpowiada NumberStyles.None stylowi) zawsze analizuje się pomyślnie. Większość pozostałych NumberStyles elementów członkowskich kontroluje, które mogą być obecne, ale nie są wymagane do obecności w ciągu wejściowym. Poniższa tabela wskazuje, jak poszczególne NumberStyles elementy członkowskie wpływają na elementy, które mogą być obecne w elemecie s.

Niezłożone wartości wyliczenia NumberStyles Elementy dozwolone w s oprócz cyfr
NumberStyles.None Tylko cyfry dziesiętne.
NumberStyles.AllowDecimalPoint Elementy dziesiętne (.) i fractional_digits . Jeśli style jednak nie zawiera flagi NumberStyles.AllowExponent , fractional_digits musi składać się tylko z jednej lub większej liczby cyfr; w przeciwnym razie OverflowException jest zgłaszana wartość .
NumberStyles.AllowExponent Znak "e" lub "E", który wskazuje notację wykładniczą wraz z exponential_digits.
NumberStyles.AllowLeadingWhite Element ws na początku s.
NumberStyles.AllowTrailingWhite Element ws na końcu selementu .
NumberStyles.AllowLeadingSign Znak dodatni przed cyframi.
NumberStyles.AllowTrailingSign Znak dodatni po cyfrach.
NumberStyles.AllowParentheses Element znaku w postaci nawiasów otaczających wartość liczbową.
NumberStyles.AllowThousands Element separatora grupy (,). Chociaż separator grupy może być wyświetlany w spliku , musi być poprzedzony tylko jedną lub większą 0 cyframi.
NumberStyles.AllowCurrencySymbol Element waluty ($).

Jeśli jest używana flaga NumberStyles.AllowHexSpecifier , s musi być wartością szesnastkową. Prawidłowe cyfry szesnastkowe to 0–9, a-f i A-F. Prefiks, taki jak "0x", nie jest obsługiwany i powoduje niepowodzenie operacji analizowania. Jedyną inną flagą, którą można połączyć, styleNumberStyles.AllowLeadingWhite i NumberStyles.AllowTrailingWhite. (Wyliczenie NumberStyles zawiera styl liczb złożonych, NumberStyles.HexNumber, który zawiera obie flagi odstępu).

Uwaga

s Jeśli parametr jest reprezentacją ciągu liczby szesnastkowej, nie może być poprzedzony żadną dekoracją (taką jak 0x lub &h), która rozróżnia ją jako liczbę szesnastkową. To powoduje zgłoszenie wyjątku przez operację analizy.

Jeśli s reprezentuje liczbę szesnastkową, Parse(String, NumberStyles) metoda interpretuje bit o wysokiej kolejności bajtu jako bit znaku.

Parametr s jest analizowany przy użyciu informacji o formatowaniu w obiekcie zainicjowanym NumberFormatInfo dla bieżącej kultury systemu. Aby użyć informacji o formatowaniu innej kultury, wywołaj przeciążenie Parse(String, NumberStyles, IFormatProvider) .

Zobacz też

Dotyczy