Int32.TryParse 方法

定義

將數字的字串表示轉換成它的對等 32 位元帶正負號的整數。 傳回指示作業是否成功的值。

多載

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int32)

嘗試將 UTF-8 字元的範圍剖析為值。

TryParse(ReadOnlySpan<Char>, Int32)

將數字的範圍表示 (使用指定樣式和特定文化特性格式) 轉換為其對等 32 位元帶正負號的整數。 傳回指示轉換是否成功的值。

TryParse(String, Int32)

將數字的字串表示轉換成它的對等 32 位元帶正負號的整數。 傳回指示轉換是否成功的值。

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int32)

嘗試將字元範圍剖析為值。

TryParse(String, IFormatProvider, Int32)

嘗試將字串剖析成值。

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

嘗試將 UTF-8 字元的範圍剖析為值。

TryParse(ReadOnlySpan<Byte>, Int32)

嘗試將包含數位字串表示的 UTF-8 字元範圍轉換為其相等的 32 位帶正負號整數。

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

將數字的範圍表示 (使用指定樣式和特定文化特性格式) 轉換為其對等 32 位元帶正負號的整數。 傳回指示轉換是否成功的值。

TryParse(String, NumberStyles, IFormatProvider, Int32)

將指定樣式和特定文化特性格式之數字的字串表示轉換成它的對等 32 位元帶正負號的整數。 傳回指示轉換是否成功的值。

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int32)

來源:
Int32.cs
來源:
Int32.cs

嘗試將 UTF-8 字元的範圍剖析為值。

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

參數

utf8Text
ReadOnlySpan<Byte>

要剖析的 UTF-8 字元範圍。

provider
IFormatProvider

提供關於 utf8Text 之特定文化特性格式資訊的物件。

result
Int32

傳回時,包含成功剖析 utf8Text 或失敗時未定義值的結果。

傳回

true 如果 utf8Text 已成功剖析,則為 ,否則為 false

適用於

TryParse(ReadOnlySpan<Char>, Int32)

來源:
Int32.cs
來源:
Int32.cs
來源:
Int32.cs

將數字的範圍表示 (使用指定樣式和特定文化特性格式) 轉換為其對等 32 位元帶正負號的整數。 傳回指示轉換是否成功的值。

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

參數

s
ReadOnlySpan<Char>

範圍,其包含代表所要轉換數字的字元。

result
Int32

如果轉換成功,這個方法會傳回包含與 s 中內含數字相等的 32 位元帶正負號整數,如果轉換失敗則為零。 如果 參數為 nullEmpty ,則轉換會失敗,且格式 style 不符合 ,或代表小於Int32.MinValue或大於Int32.MaxValue的數位。 s 這個參數未初始化便傳遞,result 中原始提供的任何值都將遭到覆寫。

傳回

如果 s 轉換成功,則為 true,否則為 false

適用於

TryParse(String, Int32)

來源:
Int32.cs
來源:
Int32.cs
來源:
Int32.cs

將數字的字串表示轉換成它的對等 32 位元帶正負號的整數。 傳回指示轉換是否成功的值。

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

參數

s
String

字串,包含要轉換的數字。

result
Int32

如果轉換成功,這個方法會傳回包含與 s 中內含數字相等的 32 位元帶正負號整數,如果轉換失敗則為零。 如果 參數為 nullEmpty ,或 不是正確的格式,或代表小於Int32.MinValue或大於Int32.MaxValue的數位,轉換就會失敗。 s 這個參數未初始化便傳遞,result 中原始提供的任何值都將遭到覆寫。

傳回

如果 s 轉換成功,則為 true,否則為 false

範例

下列範例會 Int32.TryParse(String, Int32) 以數個不同的字串值呼叫 方法。

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.

在此範例中,方法無法轉換的部分字串 TryParse(String, Int32) 如下:

  • "9432.0". 轉換失敗,因為字串不能包含小數分隔符號;它必須只包含整數位數。

  • "16,667". 轉換失敗,因為字串不能包含群組分隔符號;它必須只包含整數位數。

  • "(100)". 轉換失敗,因為字串不能包含目前文化 NumberFormatInfo.NegativeSign 特性和 NumberFormatInfo.NumberNegativePattern 屬性所定義的負號。

  • 「01FA」。 轉換失敗,因為字串不能包含十六進位數位;它必須只包含十進位數。

備註

方法 TryParse 就像 方法一樣 Parse ,但 TryParse 方法不會在轉換失敗時擲回例外狀況。 它不需要使用例外狀況處理,在無效且無法成功剖析的 事件 s 中測試 FormatException

參數 s 包含一些格式:

[ws][sign]digits[ws]

方括弧中的專案 ([ 和 ]) 是選擇性專案。 下表說明每個元素。

元素 描述
ws 選擇性空白字元。
簽署 選擇性符號。
數字 範圍從 0 到 9 的數位序列。

參數 s 會使用 NumberStyles.Integer 樣式來解譯。 除了十進位數之外,只允許開頭和尾端空格與前置符號。 若要明確定義樣式專案以及可以存在於 中的 s 特定文化特性格式資訊,請使用 Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) 方法。

參數 s 會使用針對目前系統文化特性初始化的 物件中的 NumberFormatInfo 格式資訊進行剖析。 如需詳細資訊,請參閱CurrentInfo

此方法的 TryParse 這個多載會將 參數中的所有 s 數位解譯為十進位數。 若要剖析十六進位數位的字串標記法,請呼叫 Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) 多載。

另請參閱

適用於

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int32)

來源:
Int32.cs
來源:
Int32.cs
來源:
Int32.cs

嘗試將字元範圍剖析為值。

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

參數

s
ReadOnlySpan<Char>

要剖析的字元範圍。

provider
IFormatProvider

提供關於 s 之特定文化特性格式資訊的物件。

result
Int32

當這個方法傳回時,包含成功剖析 s 的結果,或失敗時未定義的值。

傳回

true 如果 s 已成功剖析,則為 ,否則為 false

適用於

TryParse(String, IFormatProvider, Int32)

來源:
Int32.cs
來源:
Int32.cs
來源:
Int32.cs

嘗試將字串剖析成值。

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

參數

s
String

要剖析的字串。

provider
IFormatProvider

提供關於 s 之特定文化特性格式資訊的物件。

result
Int32

當這個方法傳回時,包含成功剖析 s 或失敗時未定義值的結果。

傳回

true 如果 s 已成功剖析,則為 ,否則為 false

適用於

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

來源:
Int32.cs
來源:
Int32.cs

嘗試將 UTF-8 字元的範圍剖析為值。

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

參數

utf8Text
ReadOnlySpan<Byte>

要剖析的 UTF-8 字元範圍。

style
NumberStyles

數位樣式的位元組合,可以存在於 中 utf8Text

provider
IFormatProvider

提供關於 utf8Text 之特定文化特性格式資訊的物件。

result
Int32

傳回時,包含成功剖析 utf8Text 或失敗時未定義值的結果。

傳回

true 如果 utf8Text 已成功剖析,則為 ,否則為 false

適用於

TryParse(ReadOnlySpan<Byte>, Int32)

來源:
Int32.cs
來源:
Int32.cs

嘗試將包含數位字串表示的 UTF-8 字元範圍轉換為其相等的 32 位帶正負號整數。

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

參數

utf8Text
ReadOnlySpan<Byte>

範圍,包含代表要轉換之數位的 UTF-8 字元。

result
Int32

當這個方法傳回時,如果轉換成功,則包含相當於 中 utf8Text 所含數位的 32 位帶正負號的整數值,如果轉換失敗則為零。 此參數會以未初始化的狀態來傳遞,並會覆寫任何原本在結果中提供的值。

傳回

如果 utf8Text 轉換成功,則為 true,否則為 false

適用於

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

來源:
Int32.cs
來源:
Int32.cs
來源:
Int32.cs

將數字的範圍表示 (使用指定樣式和特定文化特性格式) 轉換為其對等 32 位元帶正負號的整數。 傳回指示轉換是否成功的值。

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

參數

s
ReadOnlySpan<Char>

範圍,其包含代表所要轉換數字的字元。 此範圍使用 style 指定的樣式來解譯。

style
NumberStyles

列舉值的位元組合,表示 s 中可以存在的樣式項目。 一般會指定的值是 Integer

provider
IFormatProvider

物件,其提供關於 s 的特定文化特性格式資訊。

result
Int32

如果轉換成功,這個方法會傳回包含與 s 中內含數字相等的 32 位元帶正負號整數,如果轉換失敗則為零。 如果 參數為 nullEmpty ,則轉換會失敗,且格式 style 不符合 ,或代表小於Int32.MinValue或大於Int32.MaxValue的數位。 s 這個參數未初始化便傳遞,result 中原始提供的任何值都將遭到覆寫。

傳回

如果 s 轉換成功,則為 true,否則為 false

適用於

TryParse(String, NumberStyles, IFormatProvider, Int32)

來源:
Int32.cs
來源:
Int32.cs
來源:
Int32.cs

將指定樣式和特定文化特性格式之數字的字串表示轉換成它的對等 32 位元帶正負號的整數。 傳回指示轉換是否成功的值。

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

參數

s
String

字串,包含要轉換的數字。 這個字串使用 style 指定的樣式來解譯。

style
NumberStyles

列舉值的位元組合,表示 s 中可以存在的樣式項目。 一般會指定的值是 Integer

provider
IFormatProvider

物件,其提供關於 s 的特定文化特性格式資訊。

result
Int32

如果轉換成功,這個方法會傳回包含與 s 中內含數字相等的 32 位元帶正負號整數,如果轉換失敗則為零。 如果 參數為 nullEmpty ,則轉換會失敗,且格式 style 不符合 ,或代表小於Int32.MinValue或大於Int32.MaxValue的數位。 s 這個參數未初始化便傳遞,result 中原始提供的任何值都將遭到覆寫。

傳回

如果 s 轉換成功,則為 true,否則為 false

例外狀況

style 不是 NumberStyles 值。

-或-

style 不是 AllowHexSpecifierHexNumber 值的組合。

範例

下列範例會 Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) 使用數個不同的字串和 NumberStyles 值來呼叫 方法。

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.

備註

方法 TryParse 就像 方法一樣 Parse ,但 TryParse 方法不會在轉換失敗時擲回例外狀況。 它不需要使用例外狀況處理在無效且無法成功剖析的 事件 s 中測試 FormatException

參數 style 會定義樣式專案 (,例如空白字元或正負號) ,參數中 s 允許剖析作業成功。 它必須是列舉中的 NumberStyles 位旗標組合。 根據 的值 styles 參數可能包含下列元素:

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

或者,如果 style 參數包含 AllowHexSpecifier

[ws]hexdigits[ws]

方括弧中的專案 ([ 和 ]) 是選擇性專案。 下表說明每個元素。

元素 描述
ws 選擇性空白字元。 如果 style 包含 旗標,則空白字元可以出現在 的 s 開頭,如果包含 NumberStyles.AllowTrailingWhite 旗標,則會出現在 的 stylesNumberStyles.AllowLeadingWhite 結尾。
$ 特定文化特性的貨幣符號。 字串中的位置是由 CurrencyPositivePattern 參數的 方法 providerGetFormat 傳回之 物件的 屬性 NumberFormatInfo 所定義。 如果 style 包含 旗標, NumberStyles.AllowCurrencySymbol 則可以在 中 s 顯示貨幣符號。
簽署 選擇性符號。 如果 style 包含 或 NumberStyles.AllowTrailingSign 旗標, NumberStyles.AllowLeadingSign 則可以在 中 s 顯示符號符號。
數字 從 0 到 9 的數位序列。
, 特定文化特性的千位分隔符號。 如果包含 旗標,則 所指定 provider 文化特性的千位分隔符號可以出現在 中 sNumberStyles.AllowThousandsstyle
. 特定文化特性的小數點符號。 如果包含 旗標,則 所指定 provider 文化特性的小數點符號可能會出現在 中 sNumberStyles.AllowDecimalPointstyle
fractional_digits 數位 0 的一或多個出現次數。 只有包含 NumberStyles.AllowDecimalPoint 旗標時 style ,小數位數才會出現在 中 s
e 'e' 或 'E' 字元,表示該值是以指數標記法表示。 如果 style 包含 NumberStyles.AllowExponent 旗標,參數 s 可以代表指數標記法的數位。
hexdigits 從 0 到 f 或 0 到 F 的十六進位數位序列。

注意

中任何終止的 NUL (U+0000) 字元 s 都會被剖析作業忽略,不論引數的值 style 為何。

只有十進位數的字串 (對應至 NumberStyles.None 旗標) 一律會成功剖析。 大部分的其餘 NumberStyles 成員控制項專案可能存在,但不需要出現在這個輸入字串中。 下表指出個別 NumberStyles 成員如何影響 中 s 可能存在的專案。

非複合 NumberStyles 值 除了數位之外,還允許的專案
NumberStyles.None 僅限十進位數。
NumberStyles.AllowDecimalPoint 小數點 () 和 fractional_digits 專案。 不過, fractional_digits 只能包含一或多個 0 位數,否則方法會傳 false 回 。
NumberStyles.AllowExponent 參數 s 也可以使用指數標記法。 如果 s 以指數標記法表示數位,則必須在資料類型範圍內 Int32 表示整數,而不使用非零小數部分。
NumberStyles.AllowLeadingWhite 開頭的 sws元素。
NumberStyles.AllowTrailingWhite 結尾處的 sws專案。
NumberStyles.AllowLeadingSign 符號可以出現在 數位之前。
NumberStyles.AllowTrailingSign 符號可以出現在 數位之後。
NumberStyles.AllowParentheses 以括弧括住數值形式的 sign 元素。
NumberStyles.AllowThousands ) 元素 (千 位分隔符號。
NumberStyles.AllowCurrencySymbol $ 項目。
NumberStyles.Currency 所有元素。 參數 s 不能代表十六進位數或指數標記法中的數位。
NumberStyles.Float 開頭或結尾的 sws元素,在 開頭 s的 符號,以及小數點 () 符號。 參數 s 也可以使用指數標記法。
NumberStyles.Number ws、signthousands分隔符號 () 和小數點 (。) 元素
NumberStyles.Any 除了 以外的 s 所有樣式都不能代表十六進位數位。

NumberStyles.AllowHexSpecifier如果使用 旗標, s 必須是不含前置詞的十六進位值。 例如,「C9AF3」 會成功剖析,但 「0xC9AF3」 則不會。 唯一可以存在的 style 旗標是 NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhite 。 (NumberStyles 列舉具有複合樣式, NumberStyles.HexNumber 其中包含兩個空白字元旗標。)

參數 provider 是 實 IFormatProvider 作,例如 CultureInfo 物件或 NumberFormatInfo 物件,其 GetFormat 方法會 NumberFormatInfo 傳回 物件。 物件 NumberFormatInfo 提供有關 格式 s 的文化特性特定資訊。 如果 為 providernull ,則會 NumberFormatInfo 使用目前文化特性的物件。

另請參閱

適用於