Int32.TryParse Metoda

Definice

Převádí řetězcové vyjádření čísla na jeho ekvivalent v podobě 32bitového celého čísla se znaménkem. Vrácená hodnota označuje, jestli byla operace úspěšná.

Přetížení

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int32)

Pokusí se parsovat rozsah znaků UTF-8 na hodnotu.

TryParse(ReadOnlySpan<Char>, Int32)

Převede reprezentaci rozsahu čísla v zadaném stylu a formátu specifickém pro jazykovou verzi na jeho 32bitový celočíselný ekvivalent. Vrácená hodnota označuje, jestli převod proběhl úspěšně.

TryParse(String, Int32)

Převádí řetězcové vyjádření čísla na jeho ekvivalent v podobě 32bitového celého čísla se znaménkem. Vrácená hodnota označuje, jestli převod proběhl úspěšně.

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int32)

Pokusí se parsovat rozsah znaků na hodnotu.

TryParse(String, IFormatProvider, Int32)

Pokusí se parsovat řetězec na hodnotu.

TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Int32)

Pokusí se parsovat rozsah znaků UTF-8 na hodnotu.

TryParse(ReadOnlySpan<Byte>, Int32)

Pokusí se převést znakový rozsah UTF-8 obsahující řetězcové vyjádření čísla na jeho ekvivalent 32bitového celého čísla se znaménkem.

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Int32)

Převede reprezentaci rozsahu čísla v zadaném stylu a formátu specifickém pro jazykovou verzi na jeho 32bitový celočíselný ekvivalent. Vrácená hodnota označuje, jestli převod proběhl úspěšně.

TryParse(String, NumberStyles, IFormatProvider, Int32)

Převede řetězcovou reprezentaci čísla v zadaném stylu a formátu specifickém pro jazykovou verzi na jeho 32bitový celočíselný ekvivalent. Vrácená hodnota označuje, jestli převod proběhl úspěšně.

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int32)

Source:
Int32.cs
Source:
Int32.cs

Pokusí se parsovat rozsah znaků UTF-8 na hodnotu.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = IUtf8SpanParsable<int>::TryParse;
public static bool TryParse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider, out int result);
static member TryParse : ReadOnlySpan<byte> * IFormatProvider * int -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider, ByRef result As Integer) As Boolean

Parametry

utf8Text
ReadOnlySpan<Byte>

Rozsah znaků UTF-8, které se mají analyzovat.

provider
IFormatProvider

Objekt, který poskytuje informace o formátování specifické pro utf8Textjazykovou verzi.

result
Int32

Při vrácení obsahuje výsledek úspěšné analýzy utf8Text nebo nedefinovanou hodnotu při selhání.

Návraty

true pokud utf8Text byl úspěšně parsován, jinak hodnota false.

Platí pro

TryParse(ReadOnlySpan<Char>, Int32)

Source:
Int32.cs
Source:
Int32.cs
Source:
Int32.cs

Převede reprezentaci rozsahu čísla v zadaném stylu a formátu specifickém pro jazykovou verzi na jeho 32bitový celočíselný ekvivalent. Vrácená hodnota označuje, jestli převod proběhl úspěšně.

public:
 static bool TryParse(ReadOnlySpan<char> s, [Runtime::InteropServices::Out] int % result);
public static bool TryParse (ReadOnlySpan<char> s, out int result);
static member TryParse : ReadOnlySpan<char> * int -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), ByRef result As Integer) As Boolean

Parametry

s
ReadOnlySpan<Char>

Rozsah obsahující znaky, které představují číslo, které se má převést.

result
Int32

Když tato metoda vrátí, obsahuje 32bitovou celočíselnou hodnotu, která odpovídá číslu obsaženému v s, pokud byl převod úspěšný, nebo nula, pokud se převod nezdařil. Převod selže, pokud s parametr je null nebo Empty, není ve formátu kompatibilním s parametrem stylenebo představuje číslo menší než Int32.MinValue nebo větší než Int32.MaxValue. Tento parametr je předán neinicializován; jakákoli hodnota původně zadaná v result bude přepsána.

Návraty

true pokud s byl úspěšně převeden, jinak hodnota false.

Platí pro

TryParse(String, Int32)

Source:
Int32.cs
Source:
Int32.cs
Source:
Int32.cs

Převádí řetězcové vyjádření čísla na jeho ekvivalent v podobě 32bitového celého čísla se znaménkem. Vrácená hodnota označuje, jestli převod proběhl úspěšně.

public:
 static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] int % result);
public static bool TryParse (string s, out int result);
public static bool TryParse (string? s, out int result);
static member TryParse : string * int -> bool
Public Shared Function TryParse (s As String, ByRef result As Integer) As Boolean

Parametry

s
String

Řetězec obsahující číslo k převedení.

result
Int32

Když tato metoda vrátí, obsahuje 32bitovou celočíselnou hodnotu, která odpovídá číslu obsaženému v s, pokud byl převod úspěšný, nebo nula, pokud se převod nezdařil. Převod selže, pokud s parametr je null nebo Empty, nemá správný formát nebo představuje číslo menší než Int32.MinValue nebo větší než Int32.MaxValue. Tento parametr je předán neinicializován; jakákoli hodnota původně zadaná v result bude přepsána.

Návraty

true pokud s byl úspěšně převeden, jinak hodnota false.

Příklady

Následující příklad volá metodu Int32.TryParse(String, Int32) s několika různými řetězcovými hodnotami.

using namespace System;


   void TryToParse(String^ value)
   {
      Int32 number;
      bool result = Int32::TryParse(value, number);
      if (result) {
         Console::WriteLine("Converted '{0}' to {1}.", value, number);
      }
      else {
         if (value == nullptr) value = "";
         Console::WriteLine("Attempted conversion of '{0}' failed.", value);
      }
   }


void main()
{
      TryToParse(nullptr);
      TryToParse("160519");
      TryToParse("9432.0");
      TryToParse("16,667");
      TryToParse("   -322   ");
      TryToParse("+4302");
      TryToParse("(100);");
      TryToParse("01FA");
}
// The example displays the following output:
//      Attempted conversion of '' failed.
//      Converted '160519' to 160519.
//      Attempted conversion of '9432.0' failed.
//      Attempted conversion of '16,667' failed.
//      Converted '   -322   ' to -322.
//      Converted '+4302' to 4302.
//      Attempted conversion of '(100);' failed.
//      Attempted conversion of '01FA' failed.
using System;

public class Example
{
   public static void Main()
   {
      string[] values = { null, "160519", "9432.0", "16,667",
                          "   -322   ", "+4302", "(100);", "01FA" };
      foreach (var value in values)
      {
         int number;

         bool success = int.TryParse(value, out number);
         if (success)
         {
            Console.WriteLine($"Converted '{value}' to {number}.");
         }
         else
         {
            Console.WriteLine($"Attempted conversion of '{value ?? "<null>"}' failed.");
         }
      }
   }
}
// The example displays the following output:
//       Attempted conversion of '<null>' failed.
//       Converted '160519' to 160519.
//       Attempted conversion of '9432.0' failed.
//       Attempted conversion of '16,667' failed.
//       Converted '   -322   ' to -322.
//       Converted '+4302' to 4302.
//       Attempted conversion of '(100);' failed.
//       Attempted conversion of '01FA' failed.
open System

let values = 
   [ null; "160519"; "9432.0"; "16,667"
     "   -322   "; "+4302"; "(100);"; "01FA" ]
for value in values do
    match Int32.TryParse value with
    | true, number -> 
        printfn $"Converted '{value}' to {number}."
    | _ -> 
        printfn $"""Attempted conversion of '{if isNull value then "<null>" else value}' failed."""
         
// The example displays the following output:
//       Attempted conversion of '<null>' failed.
//       Converted '160519' to 160519.
//       Attempted conversion of '9432.0' failed.
//       Attempted conversion of '16,667' failed.
//       Converted '   -322   ' to -322.
//       Converted '+4302' to 4302.
//       Attempted conversion of '(100);' failed.
//       Attempted conversion of '01FA' failed.
Module Example
   Public Sub Main()
      Dim values() As String = { Nothing, "160519", "9432.0", "16,667",
                                 "   -322   ", "+4302", "(100);", 
                                 "01FA" }

      For Each value In values
         Dim number As Integer
    
         Dim success As Boolean = Int32.TryParse(value, number)
         If success Then
            Console.WriteLine("Converted '{0}' to {1}.", value, number)
         Else
            Console.WriteLine("Attempted conversion of '{0}' failed.", 
                              If(value ,"<null>"))
         End If     
      Next
   End Sub
End Module
' The example displays the following output to the console:
'       Attempted conversion of '<null>' failed.
'       Converted '160519' to 160519.
'       Attempted conversion of '9432.0' failed.
'       Attempted conversion of '16,667' failed.
'       Converted '   -322   ' to -322.
'       Converted '+4302' to 4302.
'       Attempted conversion of '(100)' failed.
'       Attempted conversion of '01FA' failed.

Některé z řetězců, které metoda nemůže v tomto příkladu TryParse(String, Int32) převést, jsou:

  • "9432.0". Převod selže, protože řetězec nemůže obsahovat oddělovač desetinných míst; musí obsahovat pouze integrální číslice.

  • "16,667". Převod selže, protože řetězec nemůže obsahovat oddělovače skupin; musí obsahovat pouze integrální číslice.

  • "(100)". Převod selže, protože řetězec nemůže obsahovat jiné záporné znaménko, než které je definováno vlastnostmi a NumberFormatInfo.NumberNegativePattern aktuální jazykovou NumberFormatInfo.NegativeSign verzí.

  • "01FA". Převod selže, protože řetězec nemůže obsahovat šestnáctkové číslice; musí obsahovat pouze desetinné číslice.

Poznámky

Metoda TryParse se podobá Parse metodě s tím rozdílem, že v případě selhání převodu TryParse nevyvolá výjimku. Eliminuje potřebu použití zpracování výjimek k testování objektu FormatException v případě, že s je neplatná a nelze ji úspěšně analyzovat.

Parametr s obsahuje číslo formuláře:

[ws][sign]digits[ws]

Položky v hranatých závorkách ([ a ]) jsou volitelné. Následující tabulka popisuje jednotlivé prvky.

Element Popis
Ws Volitelné prázdné místo.
sign Nepovinný znak.
Číslic Řada číslic od 0 do 9.

Parametr se s interpretuje pomocí NumberStyles.Integer stylu . Kromě desetinných číslic jsou povoleny pouze počáteční a koncové mezery společně se znaménkem na začátku. Pokud chcete explicitně definovat prvky stylu společně s informacemi o formátování specifické pro jazykovou verzi, které mohou být přítomny v s, použijte metodu Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) .

Parametr s je analyzován pomocí informací o formátování v objektu NumberFormatInfo inicializovaném pro aktuální jazykovou verzi systému. Další informace naleznete v tématu CurrentInfo.

Toto přetížení TryParse metody interpretuje všechny číslice v parametru s jako desetinné číslice. Chcete-li parsovat řetězcovou reprezentaci šestnáctkového čísla, zavolejte Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) přetížení.

Viz také

Platí pro

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int32)

Source:
Int32.cs
Source:
Int32.cs
Source:
Int32.cs

Pokusí se parsovat rozsah znaků na hodnotu.

public:
 static bool TryParse(ReadOnlySpan<char> s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = ISpanParsable<int>::TryParse;
public static bool TryParse (ReadOnlySpan<char> s, IFormatProvider? provider, out int result);
static member TryParse : ReadOnlySpan<char> * IFormatProvider * int -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), provider As IFormatProvider, ByRef result As Integer) As Boolean

Parametry

s
ReadOnlySpan<Char>

Rozsah znaků, které se mají analyzovat.

provider
IFormatProvider

Objekt, který poskytuje informace o formátování specifické pro sjazykovou verzi.

result
Int32

Když tato metoda vrátí, obsahuje výsledek úspěšné analýzy snebo nedefinovanou hodnotu při selhání.

Návraty

true pokud s byl úspěšně parsován, jinak hodnota false.

Platí pro

TryParse(String, IFormatProvider, Int32)

Source:
Int32.cs
Source:
Int32.cs
Source:
Int32.cs

Pokusí se parsovat řetězec na hodnotu.

public:
 static bool TryParse(System::String ^ s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = IParsable<int>::TryParse;
public static bool TryParse (string? s, IFormatProvider? provider, out int result);
static member TryParse : string * IFormatProvider * int -> bool
Public Shared Function TryParse (s As String, provider As IFormatProvider, ByRef result As Integer) As Boolean

Parametry

s
String

Řetězec, který se má analyzovat.

provider
IFormatProvider

Objekt, který poskytuje informace o formátování specifické pro sjazykovou verzi.

result
Int32

Když tato metoda vrátí, obsahuje výsledek úspěšné analýzy s nebo nedefinovanou hodnotu při selhání.

Návraty

true pokud s byl úspěšně parsován, jinak hodnota false.

Platí pro

TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Int32)

Source:
Int32.cs
Source:
Int32.cs

Pokusí se parsovat rozsah znaků UTF-8 na hodnotu.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = System::Numerics::INumberBase<int>::TryParse;
public static bool TryParse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style, IFormatProvider? provider, out int result);
static member TryParse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider * int -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), style As NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean

Parametry

utf8Text
ReadOnlySpan<Byte>

Rozsah znaků UTF-8, které se mají analyzovat.

style
NumberStyles

Bitové kombinace stylů čísel, které se můžou vyskytovat v nástroji utf8Text.

provider
IFormatProvider

Objekt, který poskytuje informace o formátování specifické pro utf8Textjazykovou verzi.

result
Int32

Při vrácení obsahuje výsledek úspěšné analýzy utf8Text nebo nedefinovanou hodnotu při selhání.

Návraty

true pokud utf8Text byl úspěšně parsován, jinak hodnota false.

Platí pro

TryParse(ReadOnlySpan<Byte>, Int32)

Source:
Int32.cs
Source:
Int32.cs

Pokusí se převést znakový rozsah UTF-8 obsahující řetězcové vyjádření čísla na jeho ekvivalent 32bitového celého čísla se znaménkem.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, [Runtime::InteropServices::Out] int % result);
public static bool TryParse (ReadOnlySpan<byte> utf8Text, out int result);
static member TryParse : ReadOnlySpan<byte> * int -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), ByRef result As Integer) As Boolean

Parametry

utf8Text
ReadOnlySpan<Byte>

Rozsah obsahující znaky UTF-8 představující číslo, které chcete převést.

result
Int32

Když tato metoda vrátí, obsahuje 32bitovou celočíselnou hodnotu, která odpovídá číslu obsaženému v případě úspěšného převodu, nebo nula, utf8Text pokud převod selhal. Tento parametr je předán neinicializován; jakákoli hodnota původně zadaná ve výsledku bude přepsána.

Návraty

true pokud utf8Text byl úspěšně převeden, jinak hodnota false.

Platí pro

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Int32)

Source:
Int32.cs
Source:
Int32.cs
Source:
Int32.cs

Převede reprezentaci rozsahu čísla v zadaném stylu a formátu specifickém pro jazykovou verzi na jeho 32bitový celočíselný ekvivalent. Vrácená hodnota označuje, jestli převod proběhl úspěšně.

public:
 static bool TryParse(ReadOnlySpan<char> s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result);
public:
 static bool TryParse(ReadOnlySpan<char> s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = System::Numerics::INumberBase<int>::TryParse;
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider? provider, out int result);
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider provider, out int result);
static member TryParse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider * int -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), style As NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean

Parametry

s
ReadOnlySpan<Char>

Rozsah obsahující znaky, které představují číslo, které se má převést. Rozsah se interpretuje pomocí stylu určeného parametrem style.

style
NumberStyles

Bitová kombinace hodnot výčtu, která označuje prvky stylu, které mohou být přítomny v s. Typická hodnota, která se má zadat, je Integer.

provider
IFormatProvider

Objekt, který poskytuje informace o formátování specifické pro sjazykovou verzi.

result
Int32

Když tato metoda vrátí, obsahuje 32bitovou celočíselnou hodnotu, která odpovídá číslu obsaženému v s, pokud byl převod úspěšný, nebo nula, pokud se převod nezdařil. Převod selže, pokud s parametr je null nebo Empty, není ve formátu kompatibilním s parametrem stylenebo představuje číslo menší než Int32.MinValue nebo větší než Int32.MaxValue. Tento parametr je předán neinicializován; jakákoli hodnota původně zadaná v result bude přepsána.

Návraty

true pokud s byl úspěšně převeden, jinak hodnota false.

Platí pro

TryParse(String, NumberStyles, IFormatProvider, Int32)

Source:
Int32.cs
Source:
Int32.cs
Source:
Int32.cs

Převede řetězcovou reprezentaci čísla v zadaném stylu a formátu specifickém pro jazykovou verzi na jeho 32bitový celočíselný ekvivalent. Vrácená hodnota označuje, jestli převod proběhl úspěšně.

public:
 static bool TryParse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result);
public:
 static bool TryParse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = System::Numerics::INumberBase<int>::TryParse;
public static bool TryParse (string s, System.Globalization.NumberStyles style, IFormatProvider provider, out int result);
public static bool TryParse (string? s, System.Globalization.NumberStyles style, IFormatProvider? provider, out int result);
static member TryParse : string * System.Globalization.NumberStyles * IFormatProvider * int -> bool
Public Shared Function TryParse (s As String, style As NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean

Parametry

s
String

Řetězec obsahující číslo k převedení. Řetězec se interpretuje pomocí stylu určeného parametrem style.

style
NumberStyles

Bitová kombinace hodnot výčtu, která označuje prvky stylu, které mohou být přítomny v s. Typická hodnota, která se má zadat, je Integer.

provider
IFormatProvider

Objekt, který poskytuje informace o formátování specifické pro sjazykovou verzi.

result
Int32

Když tato metoda vrátí, obsahuje 32bitovou celočíselnou hodnotu, která odpovídá číslu obsaženému v s, pokud byl převod úspěšný, nebo nula, pokud se převod nezdařil. Převod selže, pokud s parametr je null nebo Empty, není ve formátu kompatibilním s parametrem stylenebo představuje číslo menší než Int32.MinValue nebo větší než Int32.MaxValue. Tento parametr je předán neinicializován; jakákoli hodnota původně zadaná v result bude přepsána.

Návraty

true pokud s byl úspěšně převeden, jinak hodnota false.

Výjimky

style není NumberStyles hodnota.

-nebo-

style není kombinací AllowHexSpecifier hodnot a HexNumber .

Příklady

Následující příklad volá metodu Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) s několika různými řetězci a NumberStyles hodnotami.

using namespace System;
using namespace System::Globalization;

void CallTryParse(String^ stringToConvert, NumberStyles styles)
{
      Int32 number;
      CultureInfo^ provider;

      // If currency symbol is allowed, use en-US culture. 
      if (((Int32) (styles & NumberStyles::AllowCurrencySymbol)) > 0)
         provider = gcnew CultureInfo("en-US");
      else
         provider = CultureInfo::InvariantCulture;

      bool result = Int32::TryParse(stringToConvert, styles, 
                                   provider, number);
      if (result)
         Console::WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
      else
         Console::WriteLine("Attempted conversion of '{0}' failed.", 
                           Convert::ToString(stringToConvert));
}

void main()
{
      String^ numericString;
      NumberStyles styles;

      numericString = "106779";
      styles = NumberStyles::Integer;
      CallTryParse(numericString, styles);

      numericString = "-30677";
      styles = NumberStyles::None;
      CallTryParse(numericString, styles);

      styles = NumberStyles::AllowLeadingSign;
      CallTryParse(numericString, styles);

      numericString = "301677-";
      CallTryParse(numericString, styles);

      styles = styles | NumberStyles::AllowTrailingSign;
      CallTryParse(numericString, styles);

      numericString = "$10634";
      styles = NumberStyles::Integer;
      CallTryParse(numericString, styles);

      styles = NumberStyles::Integer | NumberStyles::AllowCurrencySymbol;
      CallTryParse(numericString, styles);

      numericString = "10345.00";
      styles = NumberStyles::Integer | NumberStyles::AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "10345.72";
      styles = NumberStyles::Integer | NumberStyles::AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "22,593"; 
      styles = NumberStyles::Integer | NumberStyles::AllowThousands;
      CallTryParse(numericString, styles);

      numericString = "12E-01";
      styles = NumberStyles::Integer | NumberStyles::AllowExponent;
      CallTryParse(numericString, styles); 

      numericString = "12E03";
      CallTryParse(numericString, styles); 

      numericString = "80c1";
      CallTryParse(numericString, NumberStyles::HexNumber);

      numericString = "0x80C1";
      CallTryParse(numericString, NumberStyles::HexNumber);      
      Console::ReadLine();
}
// The example displays the following output:
//      Converted '106779' to 106779.
//      Attempted conversion of '-30677' failed.
//      Converted '-30677' to -30677.
//      Attempted conversion of '301677-' failed.
//      Converted '301677-' to -301677.
//      Attempted conversion of '$10634' failed.
//      Converted '$10634' to 10634.
//      Converted '10345.00' to 10345.
//      Attempted conversion of '10345.72' failed.
//      Converted '22,593' to 22593.
//      Attempted conversion of '12E-01' failed.
//      Converted '12E03' to 12000.
//      Converted '80c1' to 32961.
//      Attempted conversion of '0x80C1' failed.
using System;
using System.Globalization;

public class StringParsing
{
   public static void Main()
   {
      string numericString;
      NumberStyles styles;

      numericString = "106779";
      styles = NumberStyles.Integer;
      CallTryParse(numericString, styles);

      numericString = "-30677";
      styles = NumberStyles.None;
      CallTryParse(numericString, styles);

      styles = NumberStyles.AllowLeadingSign;
      CallTryParse(numericString, styles);

      numericString = "301677-";
      CallTryParse(numericString, styles);

      styles = styles | NumberStyles.AllowTrailingSign;
      CallTryParse(numericString, styles);

      numericString = "$10634";
      styles = NumberStyles.Integer;
      CallTryParse(numericString, styles);

      styles = NumberStyles.Integer | NumberStyles.AllowCurrencySymbol;
      CallTryParse(numericString, styles);

      numericString = "10345.00";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "10345.72";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(numericString, styles);

      numericString = "22,593";
      styles = NumberStyles.Integer | NumberStyles.AllowThousands;
      CallTryParse(numericString, styles);

      numericString = "12E-01";
      styles = NumberStyles.Integer | NumberStyles.AllowExponent;
      CallTryParse(numericString, styles);

      numericString = "12E03";
      CallTryParse(numericString, styles);

      numericString = "80c1";
      CallTryParse(numericString, NumberStyles.HexNumber);

      numericString = "0x80C1";
      CallTryParse(numericString, NumberStyles.HexNumber);
   }

   private static void CallTryParse(string stringToConvert, NumberStyles styles)
   {
      CultureInfo provider;

      // If currency symbol is allowed, use en-US culture.
      if ((styles & NumberStyles.AllowCurrencySymbol) > 0)
         provider = new CultureInfo("en-US");
      else
         provider = CultureInfo.InvariantCulture;

      bool success = int.TryParse(stringToConvert, styles,
                                   provider, out int number);
      if (success)
         Console.WriteLine($"Converted '{stringToConvert}' to {number}.");
      else
         Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed.");
   }
}
// The example displays the following output to the console:
//       Converted '106779' to 106779.
//       Attempted conversion of '-30677' failed.
//       Converted '-30677' to -30677.
//       Attempted conversion of '301677-' failed.
//       Converted '301677-' to -301677.
//       Attempted conversion of '$10634' failed.
//       Converted '$10634' to 10634.
//       Converted '10345.00' to 10345.
//       Attempted conversion of '10345.72' failed.
//       Converted '22,593' to 22593.
//       Attempted conversion of '12E-01' failed.
//       Converted '12E03' to 12000.
//       Converted '80c1' to 32961.
//       Attempted conversion of '0x80C1' failed.
open System
open System.Globalization

let callTryParse (stringToConvert: string) styles =
    let provider =
        // If currency symbol is allowed, use en-US culture.
        if int (styles &&& NumberStyles.AllowCurrencySymbol) > 0 then
            CultureInfo "en-US"
        else
            CultureInfo.InvariantCulture

    match Int32.TryParse(stringToConvert, styles, provider) with
    | true, number ->
        printfn $"Converted '{stringToConvert}' to {number}."
    | _ ->
        printfn $"Attempted conversion of '{stringToConvert}' failed."

[<EntryPoint>]
let main _ =
    let numericString = "106779"
    let styles = NumberStyles.Integer
    callTryParse numericString styles

    let numericString = "-30677"
    let styles = NumberStyles.None
    callTryParse numericString styles

    let styles = NumberStyles.AllowLeadingSign
    callTryParse numericString styles

    let numericString = "301677-"
    callTryParse numericString styles

    let styles = styles ||| NumberStyles.AllowTrailingSign
    callTryParse numericString styles

    let numericString = "$10634"
    let styles = NumberStyles.Integer
    callTryParse numericString styles

    let styles = NumberStyles.Integer ||| NumberStyles.AllowCurrencySymbol
    callTryParse numericString styles

    let numericString = "10345.00"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint
    callTryParse numericString styles

    let numericString = "10345.72"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint
    callTryParse numericString styles

    let numericString = "22,593"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowThousands
    callTryParse numericString styles

    let numericString = "12E-01"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowExponent
    callTryParse numericString styles

    let numericString = "12E03"
    callTryParse numericString styles

    let numericString = "80c1"
    callTryParse numericString NumberStyles.HexNumber

    let numericString = "0x80C1"
    callTryParse numericString NumberStyles.HexNumber

    0

// The example displays the following output to the console:
//       Converted '106779' to 106779.
//       Attempted conversion of '-30677' failed.
//       Converted '-30677' to -30677.
//       Attempted conversion of '301677-' failed.
//       Converted '301677-' to -301677.
//       Attempted conversion of '$10634' failed.
//       Converted '$10634' to 10634.
//       Converted '10345.00' to 10345.
//       Attempted conversion of '10345.72' failed.
//       Converted '22,593' to 22593.
//       Attempted conversion of '12E-01' failed.
//       Converted '12E03' to 12000.
//       Converted '80c1' to 32961.
//       Attempted conversion of '0x80C1' failed.
Imports System.Globalization

Module StringParsing
   Public Sub Main()
      Dim numericString As String
      Dim styles As NumberStyles
      
      numericString = "106779"
      styles = NumberStyles.Integer
      CallTryParse(numericString, styles)
      
      numericString = "-30677"
      styles = NumberStyles.None
      CallTryParse(numericString, styles)
      
      styles = NumberStyles.AllowLeadingSign
      CallTryParse(numericString, styles)
      
      numericString = "301677-"
      CallTryParse(numericString, styles)
      
      styles = styles Or NumberStyles.AllowTrailingSign
      CallTryParse(numericString, styles)
      
      numericString = "$10634"
      styles = NumberStyles.Integer
      CallTryParse(numericString, styles)
      
      styles = NumberStyles.Integer Or NumberStyles.AllowCurrencySymbol
      CallTryParse(numericString, styles)

      numericString = "10345.00"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(numericString, styles)
      
      numericString = "10345.72"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(numericString, styles)

      numericString = "22,593" 
      styles = NumberStyles.Integer Or NumberStyles.AllowThousands
      CallTryParse(numericString, styles)
      
      numericString = "12E-01"
      styles = NumberStyles.Integer Or NumberStyles.AllowExponent
      CallTryParse(numericString, styles) 
          
      numericString = "12E03"
      CallTryParse(numericString, styles) 
      
      numericString = "80c1"
      CallTryParse(numericString, NumberStyles.HexNumber)
      
      numericString = "0x80C1"
      CallTryParse(numericString, NumberStyles.HexNumber)
   End Sub
   
   Private Sub CallTryParse(stringToConvert As String, styles AS NumberStyles)
      Dim number As Integer
      Dim provider As CultureInfo
      
      ' If currency symbol is allowed, use en-US culture.
      If CBool(styles And NumberStyles.AllowCurrencySymbol) Then
         provider = CultureInfo.CurrentCulture
      Else
         provider = New CultureInfo("en-US")
      End If
      
      Dim result As Boolean = Int32.TryParse(stringToConvert, styles, _
                                             provider, number)
      If result Then
         Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
      Else
         Console.WriteLine("Attempted conversion of '{0}' failed.", _
                           Convert.ToString(stringToConvert))
      End If                                                                           
   End Sub
End Module
' The example displays the following output to the console:
'       Converted '106779' to 106779.
'       Attempted conversion of '-30677' failed.
'       Converted '-30677' to -30677.
'       Attempted conversion of '301677-' failed.
'       Converted '301677-' to -301677.
'       Attempted conversion of '$10634' failed.
'       Converted '$10634' to 10634.
'       Converted '10345.00' to 10345.
'       Attempted conversion of '10345.72' failed.
'       Converted '22,593' to 22593.
'       Attempted conversion of '12E-01' failed.
'       Converted '12E03' to 12000.
'       Converted '80c1' to 32961.
'       Attempted conversion of '0x80C1' failed.

Poznámky

Metoda TryParse se podobá Parse metodě s tím rozdílem, že v případě selhání převodu TryParse nevyvolá výjimku. Eliminuje potřebu použití zpracování výjimek k testování objektu FormatException v případě, že s je neplatná a nemůže být úspěšně analyzována.

Parametr style definuje prvky stylu (například prázdné znaky nebo kladné nebo záporné znaménko), které jsou povoleny v parametru s pro úspěšnou operaci analýzy. Musí se jednat o kombinaci bitových příznaků z výčtu NumberStyles . V závislosti na hodnotě styles může parametr obsahovat následující prvky:

[ws][$][sign][digits,]digits[.fractional_digits][e[sign]digits][ws]

Nebo pokud style parametr obsahuje AllowHexSpecifier:

[ws]hexdigits[ws]

Položky v hranatých závorkách ([ a ]) jsou volitelné. Následující tabulka popisuje jednotlivé prvky.

Element Popis
Ws Volitelné prázdné místo. Prázdné znaky se mohou zobrazit na začátku, s pokud style obsahuje NumberStyles.AllowLeadingWhite příznak, nebo na konci s , pokud style obsahuje NumberStyles.AllowTrailingWhite příznak.
$ Symbol měny pro konkrétní jazykovou verzi. Jeho pozice v řetězci je definována CurrencyPositivePattern vlastností objektu NumberFormatInfo vrácenou GetFormat metodou parametru provider . Symbol měny se může zobrazit v s , pokud style obsahuje NumberStyles.AllowCurrencySymbol příznak .
sign Nepovinný znak. Symbol znaménka se může zobrazit v s , pokud style obsahuje NumberStyles.AllowLeadingSign příznaky nebo NumberStyles.AllowTrailingSign .
Číslic Řada číslic od 0 do 9.
, Oddělovač tisíců specifický pro jazykovou verzi. Oddělovač tisíců jazykové verze určené funkcí provider se může zobrazit v s , pokud style obsahuje NumberStyles.AllowThousands příznak .
. Symbol desetinné čárky specifický pro jazykovou verzi. Symbol desetinné čárky jazykové verze určené nástrojem provider se může zobrazit v s , pokud style obsahuje NumberStyles.AllowDecimalPoint příznak .
Fractional_digits Jeden nebo více výskytů číslice 0. Desetinné číslice se můžou zobrazit jen v s případě, že styleNumberStyles.AllowDecimalPoint obsahuje příznak .
E Znak "e" nebo "E", který označuje, že hodnota je vyjádřena v exponenciální notaci. Parametr s může představovat číslo v exponenciálním zápisuNumberStyles.AllowExponent, pokud style obsahuje příznak .
hexdigits Posloupnost šestnáctkových číslic od 0 do f nebo id 0 do F.

Poznámka

Operace analýzy ignoruje všechny ukončující znaky s NUL (U+0000) bez ohledu na hodnotu argumentu style .

Řetězec pouze s desítkovými číslicemi (který odpovídá příznaku NumberStyles.None ) se vždy úspěšně parsuje. Většina zbývajících NumberStyles členů řídí prvky, které mohou být, ale nejsou nutné, aby byly přítomny v tomto vstupním řetězci. Následující tabulka uvádí, jak jednotlivé NumberStyles členy ovlivňují prvky, které mohou být přítomny v snástroji .

Nesložené hodnoty NumberStyles Prvky, které jsou povoleny v s, kromě číslic
NumberStyles.None Pouze desítkové číslice.
NumberStyles.AllowDecimalPoint Desetinná čárka (.) a fractional_digits prvky. Fractional_digits však musí obsahovat pouze jednu nebo více číslic 0, nebo vrátí metoda hodnotu false.
NumberStyles.AllowExponent Parametr s může také používat exponenciální zápis. Pokud s představuje číslo v exponenciálním zápisu, musí představovat celé číslo v rozsahu Int32 datového typu bez nenulové zlomkové komponenty.
NumberStyles.AllowLeadingWhite Element ws na začátku .s
NumberStyles.AllowTrailingWhite Element ws na konci .s
NumberStyles.AllowLeadingSign Před číslicemi se může zobrazit znaménko.
NumberStyles.AllowTrailingSign Za číslicemi se může zobrazit znaménko.
NumberStyles.AllowParentheses Element sign ve formě závorek ohraničující číselnou hodnotu.
NumberStyles.AllowThousands Prvek oddělovače tisíců (,).
NumberStyles.AllowCurrencySymbol Element .$
NumberStyles.Currency Všechny prvky. Parametr s nemůže představovat šestnáctkové číslo ani číslo v exponenciálním zápisu.
NumberStyles.Float Element ws na začátku nebo na konci s, znaménko na začátku sa symbol desetinné čárky (.) Parametr s může také používat exponenciální zápis.
NumberStyles.Number Prvky ws, znaménko, oddělovač tisíců (,) a desetinná čárka (.)
NumberStyles.Any Všechny styly s výjimkou, že s nemohou představovat šestnáctkové číslo.

NumberStyles.AllowHexSpecifier Pokud se použije příznak, s musí to být šestnáctková hodnota bez předpony. Například C9AF3 úspěšně analyzuje, ale "0xC9AF3" ne. Jedinými dalšími příznaky, které se můžou v style nástroji vyskytovat, jsou NumberStyles.AllowLeadingWhite a NumberStyles.AllowTrailingWhite. (Výčet NumberStyles má složený styl , NumberStyles.HexNumberkterý obsahuje oba příznaky prázdných znaků.)

Parametr provider je IFormatProvider implementace, například CultureInfo objekt nebo NumberFormatInfo objekt, jehož GetFormat metoda vrací NumberFormatInfo objekt. Objekt NumberFormatInfo poskytuje informace specifické pro jazykovou verzi formátu .s Pokud provider je null, použije se NumberFormatInfo objekt pro aktuální jazykovou verzi.

Viz také

Platí pro