共用方式為


Int32.TryParse 方法

定義

將數位的字串表示轉換為其相等的32位帶正負號的整數。 傳回值表示作業是否成功。

多載

名稱 Description
TryParse(String, IFormatProvider, Int32)

嘗試將字串剖析成值。

TryParse(ReadOnlySpan<Char>, Int32)

將特定文化特性格式的數位範圍表示轉換為其相等的32位帶正負號整數。 傳回值表示轉換是否成功。

TryParse(String, Int32)

將數位的字串表示轉換為其相等的32位帶正負號的整數。 傳回值表示轉換是否成功。

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int32)

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

TryParse(ReadOnlySpan<Char>, 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(String, IFormatProvider, Int32)

來源:
Int32.cs
來源:
Int32.cs
來源:
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 的結果,或失敗時為未定義的值。

傳回

trues 成功解析;否則, false

適用於

TryParse(ReadOnlySpan<Char>, Int32)

來源:
Int32.cs
來源:
Int32.cs
來源:
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 位元有號整數值,若轉換失敗則為零。 若 s 參數為 nullEmpty 或 代表的數字小於 Int32.MinValue 或大於 Int32.MaxValue 則會失敗。 此參數以未初始化的方式傳遞;原本輸入 result 的任何值都會被覆寫。

傳回

trues成功轉換;否則,。 false

適用於

TryParse(String, Int32)

來源:
Int32.cs
來源:
Int32.cs
來源:
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 位元有號整數值,若轉換失敗則為零。 若s參數為nullEmpty或 ,格式不正確,或代表的數字小於 Int32.MinValue 或大於 Int32.MaxValue ,則轉換失敗。 此參數以未初始化的方式傳遞;原本輸入 result 的任何值都會被覆寫。

傳回

trues成功轉換;否則,。 false

範例

以下範例以多種不同字串值呼叫該 Int32.TryParse(String, Int32) 方法。

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.NegativeSignNumberFormatInfo.NumberNegativePattern與屬性所定義的負號以外的符號。

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

備註

TryParse 方法與 方法 Parse 相同,但 TryParse 若轉換失敗,方法不會拋出例外。 它消除了在無法成功解析的 event s 時,使用例外處理來測試 a FormatException 的必要。

s 參數包含以下形式的數字:

[ws][sign]digits[ws]

方括弧 ([ 和 ]) 中的項目是選擇性專案。 下表描述每個元素。

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

s參數是透過 NumberStyles.Integer style 來解釋的。 除了小數字數之外,只允許前置和尾端空格與前置符號。 若要明確定義風格元素及可存在 s的文化特定格式資訊,請使用該 Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) 方法。

s參數是利用為目前系統文化初始化的物件中的格式資訊NumberFormatInfo進行解析。 如需詳細資訊,請參閱CurrentInfo

此方法的超載 TryParse 將參數中 s 的所有數字解讀為十進位數字。 要解析十六進位數的字串表示,呼叫 過 Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) 載。

另請參閱

適用於

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int32)

來源:
Int32.cs
來源:
Int32.cs
來源:
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 的結果,失敗時則為未定義的值。

傳回

trueutf8Text 成功解析;否則, false

適用於

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int32)

來源:
Int32.cs
來源:
Int32.cs
來源:
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的結果,或失敗時為未定義的值。

傳回

trues 成功解析;否則, false

適用於

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

來源:
Int32.cs
來源:
Int32.cs
來源:
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 的結果,失敗時則為未定義的值。

傳回

trueutf8Text 成功解析;否則, false

適用於

TryParse(ReadOnlySpan<Byte>, Int32)

來源:
Int32.cs
來源:
Int32.cs
來源:
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

當此方法回傳時,包含 32 位元有符號整數值,若轉換成功,則等同於 的 utf8Text 數字;若轉換失敗則為零。 這個參數會未初始化傳遞;將覆寫原本在結果中提供的任何值。

傳回

trueutf8Text成功轉換;否則,。 false

適用於

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

來源:
Int32.cs
來源:
Int32.cs
來源:
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) = System::Numerics::INumberBase<int>::TryParse;
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, 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 位元有號整數值,若轉換失敗則為零。 若s參數為nullEmpty或 ,格式不符合 style,或代表的數字小於 Int32.MinValue 或大於 Int32.MaxValue ,則轉換失敗。 此參數以未初始化的方式傳遞;原本輸入 result 的任何值都會被覆寫。

傳回

trues成功轉換;否則,。 false

適用於

TryParse(String, NumberStyles, IFormatProvider, Int32)

來源:
Int32.cs
來源:
Int32.cs
來源:
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 位元有號整數值,若轉換失敗則為零。 若s參數為nullEmpty或 ,格式不符合 style,或代表的數字小於 Int32.MinValue 或大於 Int32.MaxValue ,則轉換失敗。 此參數以未初始化的方式傳遞;原本輸入 result 的任何值都會被覆寫。

傳回

trues成功轉換;否則,。 false

例外狀況

style 不是一個 NumberStyles 數值。

-或-

style不是 和 HexNumber 的組合AllowHexSpecifier

範例

以下範例以多種不同的字串與NumberStyles值呼叫該Int32.TryParse(String, NumberStyles, IFormatProvider, Int32)方法。

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時,使用例外處理來測試 a FormatException 的需求。

參數 style 定義了允許 s 在解析操作中成功時的樣式元素(如空白或正負符號)。 它必須是列舉中多個位元旗 NumberStyles 標的組合。 根據 的 style值, s 參數可能包含以下元素:

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

或者,如果參數 style 包含 AllowHexSpecifier

[ws]hexdigits[ws]

方括弧 ([ 和 ]) 中的項目是選擇性專案。 下表描述每個元素。

元素 描述
ws 選擇性的空格符。 如果包含旗幟,則可在 的s開頭出現空白,或在包含旗幟時出現在結尾NumberStyles.AllowTrailingWhitestylesNumberStyles.AllowLeadingWhitestyle
$ 特定文化特性的貨幣符號。 它在字串中的位置由CurrencyPositivePattern參數方法NumberFormatInfo回傳的GetFormat物件性質provider所定義。 貨幣s符號可出現style在包含NumberStyles.AllowCurrencySymbol旗幟時。
簽署 選擇性符號。 若style包含NumberStyles.AllowLeadingSignNumberStyles.AllowTrailingSign旗幟,標誌符號可出現s
數字 從 0 到 9 的數位序列。
, 特定文化特性的千位分隔符。 文化的provider千分隔符可出現s在包含styleNumberStyles.AllowThousands旗幟時。
. 特定文化特性的小數點符號。 provider若包含s旗幟,則可出現在 中styleNumberStyles.AllowDecimalPoint
fractional_digits 數位 0 的一或多個出現次數。 只有當 s 包含該旗幟時style,小數數字才能出現NumberStyles.AllowDecimalPoint在 中。
e 'e' 或 'E' 字元,表示值是以指數表示法表示。 若s包含style旗標,參數NumberStyles.AllowExponent可用指數符號表示數字。
六角位數 從 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 開頭sw 元素。
NumberStyles.AllowTrailingWhite 末尾s 元素。
NumberStyles.AllowLeadingSign 符號可以出現在 數字之前。
NumberStyles.AllowTrailingSign 數字 後面會出現符號。
NumberStyles.AllowParentheses 符號 元素以 括號形式包含數值。
NumberStyles.AllowThousands 千分音符()元素。
NumberStyles.AllowCurrencySymbol 元素 $
NumberStyles.Currency 所有元素。 該 s 參數無法代表十六進位數或指數符號中的數字。
NumberStyles.Float 在 的s開頭或結尾使用 ws 元素,開頭s符號,以及小數點(.) 符號。 參數 s 也可以使用指數符號。
NumberStyles.Number w、符號、千分符(,)和小數點(.)元素。
NumberStyles.Any 除了 s 不能代表十六進位數字外,所有樣式都無法代表。

NumberStyles.AllowHexSpecifier 使用該旗標, s 必須為無前綴的十六進位值。 例如,“C9AF3” 剖析成功,但 “0xC9AF3” 則不會。 唯一可能存在於 中的 style 其他旗標是 NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhite。 (列 NumberStyles 舉採用複合格式, NumberStyles.HexNumber包含兩個白格旗幟。)

參數 provider 是一個 IFormatProvider 實作,例如 CultureInfo 物件或物件 NumberFormatInfo ,其 GetFormat 方法回傳一個 NumberFormatInfo 物件。 該 NumberFormatInfo 物件提供關於 格式 s的文化特定資訊。 若provider為 ,nullNumberFormatInfo則使用 當前文化的物件。

另請參閱

適用於