Int32.Parse Metoda

Definicja

Konwertuje reprezentację ciągu liczby na 32-bitową liczbę całkowitą ze znakiem 32-bitowym.

Przeciążenia

Parse(String, NumberStyles, IFormatProvider)

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

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Konwertuje reprezentację zakresu liczby w określonym stylu i formacie specyficznym dla kultury na odpowiednik liczby całkowitej ze znakiem 32-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 32-bitowej liczby całkowitej ze znakiem.

Parse(String)

Konwertuje reprezentację ciągu liczby na 32-bitową liczbę całkowitą ze znakiem 32-bitowym.

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 32-bitowej liczby całkowitej ze znakiem.

Parse(String, NumberStyles, IFormatProvider)

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

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

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

Parametry

s
String

Ciąg zawierający liczbę, która ma zostać przekształcona.

style
NumberStyles

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

provider
IFormatProvider

Obiekt, który dostarcza informacje specyficzne dla kultury dotyczące formatu s.

Zwraca

32-bitowa liczba całkowita z podpisem odpowiada liczbie określonej w elemencie s.

Implementuje

Wyjątki

style nie jest wartością NumberStyles .

-lub-

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

s nie jest w formacie zgodnym z parametrem style.

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

-lub-

s zawiera cyfry niezerowe, ułamkowe.

Przykłady

W poniższym przykładzie użyto różnych parametrów style i provider do analizowania reprezentacji ciągów Int32 wartości. Ilustruje również niektóre różne sposoby interpretowania tego samego ciągu w zależności od kultury, której informacje o formatowaniu są używane do operacji analizowania.

using namespace System;
using namespace System::Globalization;

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

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

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

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

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

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

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

let convert (value: string) (style: NumberStyles) (provider: IFormatProvider) =
    try
        let number = Int32.Parse(value, style, provider)
        printfn $"Converted '{value}' to {number}."
    with 
    | :? FormatException ->
        printfn $"Unable to convert '{value}'."
    | :? OverflowException ->
        printfn $"'{value}' is out of range of the Int32 type."

convert "12,000" (NumberStyles.Float ||| NumberStyles.AllowThousands) (CultureInfo "en-GB")
convert "12,000" (NumberStyles.Float ||| NumberStyles.AllowThousands) (CultureInfo "fr-FR")
convert "12,000" NumberStyles.Float (CultureInfo "en-US")
convert "12 425,00" (NumberStyles.Float ||| NumberStyles.AllowThousands) (CultureInfo "sv-SE")
convert "12,425.00" (NumberStyles.Float ||| NumberStyles.AllowThousands) NumberFormatInfo.InvariantInfo
convert "631,900" (NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint) (CultureInfo "fr-FR")
convert "631,900" (NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint) (CultureInfo "en-US")
convert "631,900" (NumberStyles.Integer ||| NumberStyles.AllowThousands) (CultureInfo "en-US")

// This example displays the following output to the console:
//       Converted '12,000' to 12000.
//       Converted '12,000' to 12.
//       Unable to convert '12,000'.
//       Converted '12 425,00' to 12425.
//       Converted '12,425.00' to 12425.
//       '631,900' is out of range of the Int32 type.
//       Unable to convert '631,900'.
//       Converted '631,900' to 631900.
Imports System.Globalization

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

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

Uwagi

Parametr style definiuje elementy stylu (takie jak biały znak lub znak dodatni), które są dozwolone w parametrze s operacji analizowania, aby operacja analizy zakończyła się pomyślnie. 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,]cyfry[.fractional_digist][e[znak]exponential_digits][ws]

Lub, jeśli style zawiera AllowHexSpecifier:

[odstęp]cyfry_szesnastkowe[odstęp]

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ść NumberFormatInfo obiektu zwróconego przez GetFormat metodę parametru provider . Symbol waluty może pojawić się, 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 lub 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

fractional_digits

exponential_digits
Sekwencja cyfr od 0 do 9. W przypadku fractional_digits tylko cyfra 0 jest prawidłowa.
, Symbol separatora tysięcy specyficzny dla kultury. Separator tysięcy kultury określonej przez provider może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowThousands .
. Symbol dziesiętny specyficzny dla kultury. Symbol punktu dziesiętnego kultury określonej przez provider może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowDecimalPoint .

Tylko cyfra 0 może być wyświetlana jako cyfra ułamkowa dla operacji analizy, która zakończy się powodzeniem; jeśli fractional_digits zawiera dowolną inną cyfrę OverflowException , zostanie zgłoszony.
E Znak „e” lub „E”, który wskazuje, że wartość jest reprezentowana w zapisie wykładniczym. 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 (odpowiadający NumberStyles.None stylowi) zawsze analizuje się pomyślnie, jeśli znajduje się w zakresie Int32 typu. Większość pozostałych NumberStyles elementów członkowskich kontroluje elementy, które mogą być, ale nie muszą być obecne 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.

Niezłożone wartości wyliczenia NumberStyles Dodatkowe (poza cyframi) elementy dozwolone w parametrze s
NumberStyles.None Tylko cyfry dziesiętne.
NumberStyles.AllowDecimalPoint Elementy dziesiętne ( . ) i ułamkowe . Jednak cyfry ułamkowe muszą składać się tylko z co najmniej jednej cyfry lub OverflowException jest zgłaszana.
NumberStyles.AllowExponent Parametr s może również używać notacji wykładniczej. Jeśli s reprezentuje liczbę w notacji wykładniczej, musi reprezentować liczbę całkowitą w zakresie Int32 typu danych bez składnika ułamkowego bez zera.
NumberStyles.AllowLeadingWhite Element ws na początku s.
NumberStyles.AllowTrailingWhite Element ws na końcu selementu .
NumberStyles.AllowLeadingSign Znak dodatni może pojawić się przed cyframi.
NumberStyles.AllowTrailingSign Znak dodatni może pojawić się po cyfrach.
NumberStyles.AllowParentheses Element znaku w postaci nawiasów otaczających wartość liczbową.
NumberStyles.AllowThousands Separator tysięcy ( , ) , element.
NumberStyles.AllowCurrencySymbol Element $ .

Jeśli flaga NumberStyles.AllowHexSpecifier jest używana, s musi być wartością szesnastkową bez prefiksu. Na przykład "C9AF3" analizuje się pomyślnie, ale "0xC9AF3" nie. Jedynymi innymi flagami, które mogą być obecne, styleNumberStyles.AllowLeadingWhite i NumberStyles.AllowTrailingWhite. (Wyliczenie NumberStyles ma styl liczb złożony, NumberStyles.HexNumber, który zawiera obie flagi odstępu).

Parametr provider jest implementacją IFormatProvider , taką jak NumberFormatInfo obiekt lub CultureInfo . Parametr provider dostarcza informacje specyficzne dla kultury używane w analizowaniu. Jeśli provider jest to null, NumberFormatInfo używany jest obiekt bieżącej kultury.

Zobacz też

Dotyczy

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

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

Konwertuje reprezentację zakresu liczby w określonym stylu i formacie specyficznym dla kultury na odpowiednik liczby całkowitej ze znakiem 32-bitowym.

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

Parametry

s
ReadOnlySpan<Char>

Zakres zawierający znaki reprezentujące liczbę do przekonwertowania.

style
NumberStyles

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

provider
IFormatProvider

Obiekt, który dostarcza informacje specyficzne dla kultury dotyczące formatu s.

Zwraca

32-bitowa liczba całkowita z podpisem odpowiada liczbie określonej w elemencie s.

Implementuje

Dotyczy

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

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

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

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

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:
Int32.cs
Źródło:
Int32.cs
Źródło:
Int32.cs

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

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

Parametry

s
String

Ciąg zawierający liczbę, która ma zostać przekształcona.

provider
IFormatProvider

Obiekt, który dostarcza informacje o formatowaniu specyficznym dla kultury.s

Zwraca

32-bitowa liczba całkowita z podpisem odpowiada liczbie określonej w elemencie s.

Implementuje

Wyjątki

s nie jest poprawnym formatem.

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

Przykłady

W poniższym przykładzie występuje program obsługi zdarzeń kliknięcia przycisku w formularzu sieci Web. Używa tablicy zwróconej przez HttpRequest.UserLanguages właściwość w celu określenia ustawień regionalnych użytkownika. Następnie tworzy wystąpienie obiektu odpowiadającego CultureInfo tym ustawieniam regionalnym. NumberFormatInfo Obiekt, który należy do tego CultureInfo obiektu, jest następnie przekazywany do Parse(String, IFormatProvider) metody, aby przekonwertować dane wejściowe użytkownika na Int32 wartość.

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

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

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

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

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

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

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

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

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

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

Uwagi

To przeciążenie Parse(String, IFormatProvider) metody jest zwykle używane do konwertowania tekstu, który można sformatować na różne sposoby na Int32 wartość. Może na przykład służyć do skonwertowania tekstu wprowadzanego przez użytkownika w polu tekstowym HTML na wartość liczbową.

Parametr s zawiera liczbę formularzy:

[odstęp][znak]cyfry[odstęp]

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. Poza cyframi dziesiętnymi dopuszcza się tylko spacje początkowe i końcowe razem z wiodącym znakiem. Aby jawnie zdefiniować elementy stylu, które mogą być obecne w sprogramie , użyj Int32.Parse(String, NumberStyles, IFormatProvider) metody .

Parametr provider jest implementacją IFormatProvider , taką jak NumberFormatInfo obiekt lub CultureInfo . Parametr provider dostarcza informacje specyficzne dla kultury dotyczące formatu s. Jeśli provider jest to null, NumberFormatInfo używany jest obiekt bieżącej kultury.

Zobacz też

Dotyczy

Parse(String)

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

Konwertuje reprezentację ciągu liczby na 32-bitową liczbę całkowitą ze znakiem 32-bitowym.

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

Parametry

s
String

Ciąg zawierający liczbę, która ma zostać przekształcona.

Zwraca

32-bitowa liczba całkowita ze znakiem odpowiadającym liczbie zawartej w elemencie s.

Wyjątki

s nie jest w poprawnym formacie.

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

Przykłady

W poniższym przykładzie pokazano, jak przekonwertować wartość ciągu na 32-bitową wartość całkowitą ze znakiem Int32.Parse(String) przy użyciu metody . Wynikowa wartość całkowita jest następnie wyświetlana w konsoli programu .

using namespace System;

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

public class Example
{
   public static void Main()
   {
      string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127",
                          "0xFA1B", "163042", "-10", "007", "2147483647",
                          "2147483648", "16e07", "134985.0", "-12034",
                          "-2147483648", "-2147483649" };
      foreach (string value in values)
      {
         try {
            int number = Int32.Parse(value);
            Console.WriteLine("{0} --> {1}", value, number);
         }
         catch (FormatException) {
            Console.WriteLine("{0}: Bad Format", value);
         }
         catch (OverflowException) {
            Console.WriteLine("{0}: Overflow", value);
         }
      }
   }
}
// The example displays the following output:
//       +13230 --> 13230
//       -0 --> 0
//       1,390,146: Bad Format
//       $190,235,421,127: Bad Format
//       0xFA1B: Bad Format
//       163042 --> 163042
//       -10 --> -10
//       007 --> 7
//       2147483647 --> 2147483647
//       2147483648: Overflow
//       16e07: Bad Format
//       134985.0: Bad Format
//       -12034 --> -12034
//       -2147483648 --> -2147483648
//       -2147483649: Overflow
open System

let values =
    [ "+13230"; "-0"; "1,390,146"; "$190,235,421,127"
      "0xFA1B"; "163042"; "-10"; "007"; "2147483647"
      "2147483648"; "16e07"; "134985.0"; "-12034"
      "-2147483648"; "-2147483649" ]

for value in values do
    try
        let number = Int32.Parse value
        printfn $"{value} --> {number}"
    with 
    | :? FormatException ->
        printfn $"{value}: Bad Format"
    | :? OverflowException ->
        printfn $"{value}: Overflow"
    

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

Uwagi

Parametr s zawiera liczbę formularzy:

[odstęp][znak]cyfry[odstęp]

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

Element Opis
ws Opcjonalny odstęp.
znak Opcjonalny znak.
cyfry Sekwencja cyfr od 0 do 9.

Parametr s jest interpretowany przy użyciu NumberStyles.Integer stylu. Poza cyframi dziesiętnymi dopuszcza się tylko spacje początkowe i końcowe razem z wiodącym znakiem. Aby jawnie zdefiniować elementy stylu, które mogą być obecne w sprogramie , użyj Int32.Parse(String, NumberStyles) metody lub Int32.Parse(String, NumberStyles, IFormatProvider) .

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

Zobacz też

Dotyczy

Parse(ReadOnlySpan<Char>, IFormatProvider)

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

Analizuje zakres znaków w wartości.

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

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:
Int32.cs
Źródło:
Int32.cs

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

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

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:
Int32.cs
Źródło:
Int32.cs
Źródło:
Int32.cs

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

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

Parametry

s
String

Ciąg zawierający liczbę, która ma zostać przekształcona.

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

32-bitowa liczba całkowita z podpisem odpowiada liczbie określonej w elemencie s.

Wyjątki

style nie jest wartością NumberStyles .

-lub-

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

s nie jest w formacie zgodnym z parametrem style.

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

-lub-

s zawiera cyfry niezerowe, ułamkowe.

Przykłady

W poniższym przykładzie Int32.Parse(String, NumberStyles) użyto metody , aby przeanalizować reprezentacje ciągu kilku Int32 wartości. W przykładzie bieżącą kulturą jest en-US.

using namespace System;
using namespace System::Globalization;

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

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

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

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

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

let convert value (style: NumberStyles) =
    try
        let number = Int32.Parse(value, style)
        printfn $"Converted '{value}' to {number}."
    with 
    | :? FormatException ->
        printfn $"Unable to convert '{value}'."
    | :? OverflowException ->
        printfn $"'{value}' is out of range of the Int32 type."

convert "104.0" NumberStyles.AllowDecimalPoint
convert "104.9" NumberStyles.AllowDecimalPoint
convert " $17,198,064.42" (NumberStyles.AllowCurrencySymbol ||| NumberStyles.Number)
convert "103E06" NumberStyles.AllowExponent
convert "-1,345,791" NumberStyles.AllowThousands
convert "(1,345,791)" (NumberStyles.AllowThousands ||| NumberStyles.AllowParentheses)


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

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

Uwagi

Parametr style definiuje elementy stylu (takie jak biały znak, symbol znaku dodatniego lub ujemnego lub symbol separatora tysięcy), które są dozwolone w parametrze s operacji analizowania, która zakończy się pomyślnie. Musi być kombinacją flag bitowych z wyliczenia NumberStyles . W zależności od wartości parametr może styles zawierać następujące elementy:

[odstęp][$][znak][cyfry,]cyfry[.cyfry_ułamkowe][e[znak]cyfry_potęgowe][odstęp]

Lub, jeśli style zawiera AllowHexSpecifier:

[odstęp]cyfry_szesnastkowe[odstęp]

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.CurrencyNegativePattern właściwości i NumberFormatInfo.CurrencyPositivePattern 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

fractional_digits

exponential_digits
Sekwencja cyfr od 0 do 9. W przypadku fractional_digits tylko cyfra 0 jest prawidłowa.
, Symbol separatora tysięcy specyficzny dla kultury. Separator tysięcy bieżącej kultury może pojawić się, s jeśli style zawiera flagę NumberStyles.AllowThousands .
. 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 . Tylko cyfra 0 może być wyświetlana jako cyfra ułamkowa dla operacji analizy, która zakończy się powodzeniem; jeśli fractional_digits zawiera dowolną inną cyfrę OverflowException , zostanie zgłoszony.
E Znak „e” lub „E”, który wskazuje, że wartość jest reprezentowana w zapisie wykładniczym. 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 (odpowiadający NumberStyles.None stylowi) zawsze analizuje się pomyślnie, jeśli znajduje się w zakresie Int32 typu. Większość pozostałych NumberStyles elementów członkowskich kontroluje elementy, które mogą być, ale nie muszą być obecne 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.

Wartość wyliczenia NumberStyles Dodatkowe (poza cyframi) elementy dozwolone w parametrze s
None Tylko element cyfry .
AllowDecimalPoint Elementy dziesiętne ( . ) i ułamkowe .
AllowExponent Parametr s może również używać notacji wykładniczej.
AllowLeadingWhite Element ws na początku s.
AllowTrailingWhite Element ws na końcu selementu .
AllowLeadingSign Element znaku na początku selementu .
AllowTrailingSign Element znaku na końcu elementu s.
AllowParentheses Element znaku w postaci nawiasów otaczających wartość liczbową.
AllowThousands Separator tysięcy ( , ) , element.
AllowCurrencySymbol Element $ .
Currency Wszystkie. Parametr s nie może reprezentować liczby szesnastkowej ani liczby w notacji wykładniczej.
Float Element ws na początku lub na końcu s, znak na początku s, i symbol dziesiętny ( . ). Parametr s może również używać notacji wykładniczej.
Number wsElementy separatora , sign, tysięcy ( , ), i punktu dziesiętnego ( . ).
Any Wszystkie style, z wyjątkiem s nie mogą reprezentować liczby szesnastkowej.

Jeśli flaga NumberStyles.AllowHexSpecifier jest używana, s musi być wartością szesnastkową bez prefiksu. Na przykład "C9AF3" analizuje się pomyślnie, ale "0xC9AF3" nie. Jedyne inne flagi, które można połączyć z parametrem s , to NumberStyles.AllowLeadingWhite i NumberStyles.AllowTrailingWhite. (Wyliczenie NumberStyles zawiera styl liczb złożonych, NumberStyles.HexNumber, który zawiera obie flagi odstępu).

Parametr s jest analizowany przy użyciu informacji o formatowaniu w obiekcie zainicjowanym NumberFormatInfo dla bieżącej kultury systemu. Aby określić kulturę, której informacje dotyczące formatowania są używane do operacji analizowania, wywołaj Int32.Parse(String, NumberStyles, IFormatProvider) przeciążenie.

Zobacz też

Dotyczy